3

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

2
  • 1
    Show more code. Where is value declared? Commented Apr 22, 2012 at 19:27
  • I assume value is std::string as you wrote. Are you sure there are no trailing/leading spaces in value? Commented Apr 22, 2012 at 19:30

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad it helped. Note that if value was of type std::string the code you posted would be working as you expected (as chris posted in his answer).
3

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

0

It seems that SearchInfoString returns a char *, based on the way you use it with Com_Printf. Therefore you can just use strcmp() to compare value to "0.3c". For example:

if (strcmp(value, "0.3c") != 0)
{
    // Print warning
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.