How do I implement 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).
I use
std::string::compare
wrapped in utility method like below:Who needs anything else? Pure STL!
Just for completeness, I will mention the C way to do it:
(originally posted by Yaseen Rauf here, markup added)
For a case-insensitive comparison, use
strnicmp
instead ofstrncmp
.This is the C way to do it, for C++ strings you can use the same function like this:
If you're using Boost, you can do it with boost string algorithms + boost lexical cast:
Like most boost libraries, string algorithm & lexical cast are header-only, there's nothing to link in.
This kind of approach, like many of the other answers provided here is ok for very simple tasks, but in the long run you are usually better off using a command line parsing library. Boost has one (Boost.Program_options), which may make sense if you happen to be using Boost already.
Otherwise a search for "c++ command line parser" will yield a number of options.
Why not use gnu getopts? Here's a basic example (without safety checks):
For the following command:
You will get
Code I use myself: