C++ Compare char array with string

后端 未结 6 1755
悲哀的现实
悲哀的现实 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

    You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

    So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

    Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

    IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

    The C way of doing this is to use the strcmp function:

    strcmp(var1, "dev");
    

    This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

    So to compare for equality you need to do one of these:

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

    However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

    std::string var1 = getenv("myEnvVar");
    
    if(var1 == "dev")
    {
       // do stuff
    }
    

    Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

提交回复
热议问题