C++ Compare char array with string

后端 未结 6 1764
悲哀的现实
悲哀的现实 2020-11-29 05:06

I\'m trying to compare a character array against a string like so:

const char *var1 = \" \";
var1 = getenv(\"myEnvVar\");

if(var1 == \"dev\")
{
   // do stu         


        
6条回答
  •  囚心锁ツ
    2020-11-29 05:45

    Use strcmp() to compare the contents of strings:

    if (strcmp(var1, "dev") == 0) {
    }
    

    Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.

提交回复
热议问题