-3

I can't seem to compare what I believe are strings.

My function looks like the following:

void handleMessage(AdafruitIO_Data *data) {
  Serial.printf("\nreceived <- %s", data->value());
  if (data->value() == "OPEN") {
    Serial.printf("\nIt worked!");
  }
}

When printed, data->value() prints what I expect it to, but when I compare it like this data->value() == "OPEN" it doesn't work. What is the right way to do this, and why isn't the above working?

I have attempted to use strcmp() as suggested by How do I properly compare strings?

void handleMessage(AdafruitIO_Data *data) {
  Serial.printf("\nreceived <- %s", data->value());
  if (strcmp(data->value() == "OPEN")) {
    Serial.printf("\nIt worked!");
  }
}

However I get:

FileName:48: error: cannot convert 'bool' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

It isn't a boolean when it is printed. From my example it prints: received <- OPEN

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
alairock
  • 1,826
  • 1
  • 21
  • 28
  • @MFisherKDX I had seen/tried was that too, but that also doesn't seem to work. – alairock Sep 07 '18 at 21:00
  • post the definition of `AdafruitIO_Data` and how you are calling `strcmp()`. Also, please turn on compiler warnings as this will help you in the long run. – MFisherKDX Sep 07 '18 at 21:04
  • Using the Arduino IDE, not sure how/if you can do that. I'll update my post to include your suggestion. – alairock Sep 07 '18 at 21:05
  • That's not how you use `strcmp`. – gre_gor Sep 07 '18 at 21:11
  • 1
    file->preferences->compiler warnings – MFisherKDX Sep 07 '18 at 21:12
  • Did you look up the API for `strcmp`? Reference can be found here: http://www.cplusplus.com/reference/cstring/strcmp/ strcmp takes two arguments both are `char *` (pointer to a char), you are supplying it with a boolean expression that boils down to a `bool` – bigwillydos Sep 07 '18 at 21:12

1 Answers1

3

When printed, data->value() prints what I expect it to, but when I compare it like this data->value() == "OPEN" it doesn't work. What is the right way to do this, and why isn't the above working?

strcmp takes two arguments both are char * (pointer to a char), you are supplying it with a boolean expression that boils down to a bool

Reference for strcmp can be found here

Assuming that AdafruitIO_Data is as defined here and that you've included string.h

void handleMessage(AdafruitIO_Data *data) {
  Serial.printf("\nreceived <- %s", data->value());
  if (!strcmp(data->value(), "OPEN")) {
    Serial.printf("\nIt worked!");
  }
}
bigwillydos
  • 1,321
  • 1
  • 10
  • 15