简体   繁体   中英

Comparison in string literal results in inspecified behavior - C++

I'm using eclipse. I declared #define OUTPUT_FLAG "-o" and then, I have the main : int main(int argc, char **argv) after that I write:

    for (int i = 1; i < argc; i+=2)
    {
        if(argv[i]==INPUT_FLAG)
        {
            cout<<"input flag\n";
            input_file=argv[i+1];
        }
    }

and there I get the error on the subject. Can you help me here? Thank you

You cannot compare strings with == in C++. You either have to use strcmp or convert them to std::string s and then use the == operator. That is, either:

if (!strcmp(argv[i], INPUT_FLAG))

or

if (std::string(argv[i]) == INPUT_FLAG)

You can't compare C strings ( char * ) using the == operator, as that operator only checks for pointer equality (rather than dereferencing the pointer and comparing each character one by one). Use strcmp() , or convert the string in argv[] to a C++ string type first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM