Comparing const char to a string
11,243
Solution 1
If value is of type const char*, expression
value != "0.3c"
is comparing two pointers (addresses), not strings. You want to compare string and a string literal so can use strcmp
:
if(strcmp(value, "0.3c"))
{
// strings are not equal
}
else
{
// strings are equal
}
Bear in mind that preferred string type in C++ is std::string
.
Solution 2
Use an std::string
for value
.
std::string value = SearchInfoString(msg, "shortversion");
Then, you can compare it normally. If you cannot use a string at all for whatever reason (the return value can be converted), use strcmp
.
if (strcmp (value, "0.3c") != 0)
{
...
}
Comments
-
JorgenPhi almost 2 years
I have an issue comparing a const char to a string... If I use Com_Printf ("%s", value); It returns what I want (0.3c), but how can I convert value to a string and compare that to 0.3c? This is what I have:
value = SearchInfostring(msg, "shortversion"); if (value != "0.3c") { Com_Printf (MSG_WARNING, Com_Printf (MSG_WARNING, "> WARNING: Value: Should be 0.3c, is: %s \n", value); //Run stuff }
That returns: WARNING: Value: Should be 0.3c, is: 0.3c
-
Bojan Komazec about 12 yearsI'm glad it helped. Note that if
value
was of typestd::string
the code you posted would be working as you expected (as chris posted in his answer).