比较AdafruitIO_Data对象的字符串[重复]

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我似乎无法比较我认为的字符串。

我的功能如下所示:

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

打印时,data->value()打印出我期望的内容,但是当我比较它时,data->value() == "OPEN"它不起作用。这样做的正确方法是什么,为什么上述工作不正常?

我试图按照strcmp()的建议使用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!");
  }
}

但是我得到:

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

它在打印时不是布尔值。从我的例子中打印出来:received <- OPEN

arduino adafruit
1个回答
3
投票

打印时,data-> value()打印出我期望的内容,但是当我像这样的数据 - > value()==“OPEN”进行比较时,它不起作用。这样做的正确方法是什么,为什么上述工作不正常?

strcmp接受两个参数都是char *(指向char的指针),你为它提供一个boolean表达式,归结为bool

可以找到strcmp的参考资料here

假设AdafruitIO_Data定义为here并且你已经包括string.h

void handleMessage(AdafruitIO_Data *data) {
  Serial.printf("\nreceived <- %s", data->value());
  if (!strcmp(data->value(), "OPEN")) {
    Serial.printf("\nIt worked!");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.