3

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?

clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • Did you sleep well? Coming from this post: http://stackoverflow.com/questions/2931704/how-to-compare-string-with-const-char It's quite a easy mistake. – clankill3r Nov 14 '13 at 13:57

2 Answers2

9

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.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
2

std::strcmp returns 0 when strings are the same, and value less than 0 or greater than 0 when strings differ. So you might change your code for something like this:

if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") != 0) {
  printf("indeed, strings are different\n");

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

http://en.cppreference.com/w/cpp/string/byte/strcmp


How can i get a valid compare?

if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") == 0) {
      printf("strings are equal lexicographically\n");
4pie0
  • 29,204
  • 9
  • 82
  • 118