开发者

C++ command line argument comparison

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 wor开发者_开发技巧king 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


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.


./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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜