• Advertisement

Archived

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

extracting numbers from argv[]

This topic is 5214 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
read up on the function atoi().


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


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

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

  • Advertisement