C++ command line argument comparison

11,147

Solution 1

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.

Solution 2

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

Share:
11,147
Anonymous
Author by

Anonymous

Updated on June 04, 2022

Comments

  • Anonymous
    Anonymous about 2 years

    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