C++ Compare char array with string

Chris Klepeis picture Chris Klepeis · Aug 25, 2009 · Viewed 148.2k times · Source

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

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

if(var1 == "dev")
{
   // do stuff
}

This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).

edit: we've tried

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

and

if(strncmp(var1, "dev", 3) == 0)

Thanks

edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.

Answer

John Millikin picture John Millikin · Aug 25, 2009

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.