Search code examples
c++charconstantsstrcmp

compare const char * with strcmp


I compare a const char * to a string and for some reason it always succeeds.

    if (std::strcmp(t->detectColor->name, "ghghjg") != 0) {
        printf("XXXXXXXXXXX\n");
        // check if it was allready a sequencer
        if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") != 0) {
          printf("what is going on?\n");

The detectColor name is always something like green or blue, and t->className is "ofxDTangibleBase" for example. Still it prints

XXXXXXXXXXX
what is going on?

in the console. How can i get a valid compare?


Solution

  • According to cplusplus.com:

    Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

    Or said differently by cppreference.com:

    Return value

    • Negative value if lhs is less than rhs.
    • 0​ if lhs is equal to rhs.
    • Positive value if lhs is greater than rhs.

    So, in your code, strcmp(t->detectColor->name, "ghghjg") will return something different than 0. As a consequence, "XXXXXXXXXXX" will be printed.

    You only have to change:

    if (std::strcmp(t->detectColor->name, "ghghjg") != 0)
    

    to

    if (std::strcmp(t->detectColor->name, "ghghjg") == 0)
    

    And the same for the other comparison.