سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top