arguments [Archive] - C Board

PDA

View Full Version : arguments


mungyun
04-09-2002, 10:18 PM
This may seem simple but i cant figure it out:
I want to be able to pass a single argument to my program and i can do this, i can also get it to print to stdout but when i try to use an 'if' statment with argv[1] it just goes to my else even if it matches with the if.
an example similar to my basic prog:

int main(int argc, char *argv[])
{
cout<<argv[1]<<endl; //this prints out "foo"
//assuming i used arg "foo"

if(argc !=2)
{
cout<<"blah\n";
return 0;
}

else if(argv[1] == "foo")
{
cout<<"foo\n";
return 0;
}

else
cout<<"no argument\n"; //this is what prints
//even if i use "foo"
//as an argument
return 0;
}
sorry if this seems too basic but i am getting a headache trying to figure it out. What am i doing incorrectly?

-mungyun

Deckard
04-10-2002, 05:29 AM
Originally posted by mungyun
This may seem simple but i cant figure it out:
<snip>
else if(argv[1] == "foo")
When you want to compare strings, use strcmp or strncmp (man pages available for both). Your 'else if' should be:
else if ( strcmp(argv[1], "foo") == 0 )Hope that helps,