简体   繁体   中英

C++ arguments comparison

Hello I am trying to read some arguments and process them but when i try to read arguments via if else ladder a problem occurs

int main (int argc, char *argv[])
{
cout << argv[1] << endl;
if (argv[1] == "process")
    cout << "yes" << endl;
else
    cout << "no" << endl;
}

This code outputs:

process

no

Do you know why the output is no instead of yes ?

By the way I tried to convert either one of them to a string and compared it with another surprisingly it worked, even though I couldn't figure out why.

argv[1] is a pointer, actually a char * (see the definition char *argv[] ), and in your code "process" (which is a const char [] ) also decays to a const char * , so you are basically comparing two char * .

Since char * are simply pointers, then you are comparing addresses, not "string", and obviously argv[1] and "process" are not stored at the same address.

If you convert one of the two to std::string , then you are comparing a std::string and char * (or const char * ), and std::string has an overloaded operator== for char * so it works.

You could compare "C strings" (aka char arrays) using strcmp or strncmp .

argv[1] == "process" compares pointers. Use strcmp to compare the strings behind the pointers:

#include <string.h>

int main (int argc, char *argv[])
{
cout << argv[1] << endl;
if (strcmp(argv[1],"process")==0)
    cout << "yes" << endl;
else
    cout << "no" << endl;
}

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