Saturday, May 22, 2010

Using argv in C++ to get ints?

I have a program that has main(int argc, char *argv[])





if say, my line was ./a.out baby 42





I know I can store "baby" in a string by saying





string a=arg[1];


cout%26lt;%26lt;a; //would pring out "baby"





int b=???


cout%26lt;%26lt;b; //I want to print 42





I want to store 42 as in int in C++ but argv takes c-style strings. please help.

Using argv in C++ to get ints?
the arguments (arg[1], arg[2] etc) are of type char *, that's a C string. You have to convert the char* to an integer. There are several ways to do that, i.e. with atoi() or with strtoul().





int i=(int)strtoul(arg[2], 0, 0);





string a=arg[1];


this works, because the compiler knows how to build a std::string from a char*. (There's an overloaded assignment operator which accepts a char * parameter).
Reply:There are lots of ways to do this. I'd use atoi().





int b=atoi(argv[1]);





You might also look at strtoul, for example. Also
Reply:take say you had 342. If you wanted to convert it to an int, you'd take the first character 4 and subtract the character 0 from it.


'3' - '0' = the integer 3, now multiply that times 100.


'4' -'0' = the integer 4, now multiply that times 10.


'2' - '0' = the integer 2, you don't have to multiply this one, now add the three together.





Hope that helps!
Reply:Convert the string "42" into and integer.
Reply:The variable a is declared as a std::string, so it's a real string, not a pointer-to-char.





To convert a string (or anything, really) to a number (or anything, really), I recommend the use of boost::lexical_cast [1]. To use it, you do this (with the example and coding style [2] you had above):





int b = lexical_cast%26lt;int%26gt;(argv[2]);





Of course you can replace the int with, say, a double and it will convert the string (or whatever) to a double.





You will have to install Boost in order to use this highly useful facility, but in my view, that is a small price to pay. You can find installation instructions at [3].


No comments:

Post a Comment