extracting numbers from argv[]

Started by
3 comments, last by Bacardi34 20 years, 5 months ago
Hi, I have a progam where one of the -flags passes in a number after it. I am having trouble trying to figure out how to get that number back out of argv[] though. I know that its a char but without making a huge switch statement for every possible number there is or a large parsing function im kinda lost. Im sure there must be an easy way around this, can anyone help me out? Here is a small test program a wrote that demonstrates the problem.


int main( int argc, char **argv )
{
int a, i;
for( i = 0; i < argc; i++ )
{
if( !strcmp( argv[i], "-a" ))
a = argv[i+1];
}
fprintf( stdout, "a:%d\n", a );
return 1;
}
changing a = argv[i+1] to a = (int)argv[i+1] or a = *argv[i+1] just makes a the value of the char its self. Thanks for the help!
Advertisement
read up on the function atoi().

"Sneftel is correct, if rather vulgar." --Flarelocke
Awesome thanks
Just so you know,

argv[0] 
is the program name (since it too is considered as a param). Thus, there is always at least 1 argument.
quote:Original post by Sneftel
read up on the function atoi().

And then disregard it. The problem with atoi is that, for an input string yielding an out-of-range integer, the result is undefined behaviour. sprintf and C++ stringstreams both provide for safer alternatives.

This topic is closed to new replies.

Advertisement