views:

120

answers:

2

I am doing some validation of the arguments passed by command line in C++ and am having some difficulties.

I am doing like so

./a.exe inputfile.txt outputfile.txt 16 flush_left

And I am trying to do the validation like so

if(argv[4] == "flush_left" || argv[4] == "flush_justify" || argv[4] == "flush_right"){

And its not working out as planned. Though I am not seeing why this won't work. From everything I've read and seen that should be just fine

+10  A: 

try:

std::string argv4 = argv[4];
if(argv4 == "flush_left" || argv4 == "flush_justify" || argv4 == "flush_right"){
  //...
}

or (untested):

if( argc >=4 && (!strcmp(argv[4],"flush_left")  || !strcmp(argv[4],"flush_justify") || !strcmp(argv[4],"flush_right")) ) {
  //...
}

argv[4] has type char*, and string literals have type const char*, you cant compare the content of those types (=text) using the == operator, you would have to use something like strcmp or the std::string class instead.

Using == on char* compares the address of the variables, not the content.

smerlin
+1 : I was a bit hasty, removed my answer.
Edward Leno
Another possibility is to use strcmp(). I'd go with std::string, as you have shown, however.
Brian Neal
"strcmp/strncmp returns the amount of characters which don't match" - that's a brave assertion. Care to state your source for that?
paxdiablo
Thanks man this is solved
Anonymous
@pax Brave is one word for it :)
Michael Mrozek
Oh, well, smerlin won't fix the error, I guess we'll have to do it ourselves :-)
paxdiablo
I think `strncmp()` is inappropriate - use `strcmp()`. If you use `strncmp()`, then the argument `flush_leftwards` would be treated as equal to `flush_left`. If you do use `strncmp()`, use (for example): `strncmp(argv[4], "flush_left", sizeof("flush_left"))` (equivalent to 11 for the third argument) as it checks that the last character is a '`\0`'.
Jonathan Leffler
Good point, @Jonathon. Since both `argv[n]` (where 0 < `n` < `argc`) and `"xyz"` will always be null-terminated, it's a waste using `strncmp`.
paxdiablo
yes, using `strcmp` is ok, but you will have to add a check for `argc>=4` then, or shit happens, i will edit the answer to reflect this.
smerlin
@paxdiablo: hmm, i stand corrected. I never used strcmp for anything else besides checking if 2 strings are equal, so my memories about the excact api of strcmp were hmm ...corrupted.
smerlin
+1  A: 

./a.exe inputfile.txt outputfile.txt 16 flush_left

A zero based argv gives you: argv[0] = a.exe argv[1] = inputfile.txt argv[2] = outputfile.txt argv[3] = 16 argv[4] = flush_left

so the index is correct, however you should use strcmp(stringa, stringb) and make sure that returns 0 instead.

Nick