Archived

This topic is now archived and is closed to further replies.

Bacardi34

extracting numbers from argv[]

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites