C++ Compare char array with string

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

    "dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.

    Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.

提交回复
热议问题