首页 > 解决方案 > 如何比较#define定义的字符串和整数?

问题描述

我有以下 C++ 代码:

#define VERSION        1
#define TYPE           "this"
...

bool update(const char* json) {
    ...
    const char* theType = doc["type"];     // "this"
    int theVer          = doc["version"];  // 2

    //int ourVer        = VERSION;
    //char ourType[]    = TYPE;

    if ( (theVer > VERSION) && (theType == TYPE) ) {
        return true
    } else {
        return false;
    }
}

我可以同时打印theTypetheVer,但我无法成功地将它们与常量进行比较。我还尝试与强制转换的常量(已注释掉)进行比较,但无济于事。

如何比较#define 定义的字符串和整数?

顺便提一句。这是在 ArduinoIDE 中编码的。

标签: c++arduinoc-preprocessor

解决方案


theType == TYPE比较两个指针。当且仅当地址相同时,它才返回 true,这里不是这种情况。

改用strcmp

if (theVer > VERSION && std::strcmp(theType, TYPE) == 0) {
    // ...
}

strcmp三向比较实际字符串,返回一个数字,即< 0, == 0,或者> 0当第一个字符串小于、等于或大于第二个字符串时。你需要#include <cstring>这个。


推荐阅读