Daryl Spitzer Daryl Spitzer - 4 months ago 60
C++ Question

How do I check if a C++ <string> starts with a certain string, and convert a substring to an int?

How do I do the following (Python pseudocode) in C++?

if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])

(For example, if argv[1] is '--foo=98', then foo_value is 98.)

Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool. (I'd rather not have to learn how to link in and use Boost for a minor change.)


Using boost string algorithms + boost lexical cast:

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter

Like most boost libraries, string algorithm & lexical cast are header-only, there's nothing to link in.