c++ - 如何比较#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;
}
}
我可以同时打印theType
和theVer
,但我无法成功地将它们与常量进行比较。我还尝试与强制转换的常量(已注释掉)进行比较,但无济于事。
如何比较#define 定义的字符串和整数?
顺便提一句。这是在 ArduinoIDE 中编码的。
解决方案
theType == TYPE
比较两个指针。当且仅当地址相同时,它才返回 true,这里不是这种情况。
改用strcmp
:
if (theVer > VERSION && std::strcmp(theType, TYPE) == 0) {
// ...
}
strcmp
三向比较实际字符串,返回一个数字,即< 0
, == 0
,或者> 0
当第一个字符串小于、等于或大于第二个字符串时。你需要#include <cstring>
这个。
推荐阅读
- javascript - 无法为在 JavaScript 中创建的 div 按钮设置值
- java - 如何使用邮递员在 keyclaok 中添加新用户?
- php - 实现变量回调错误消息
- bdd - 空手道 SET 功能未设置值
- mapbox - 为什么添加 3000 个或更多标记时,mapbox 地图会如此缓慢?
- angular - 获取 TypeError:使用注入器运行业力测试时无法读取 undefine 的属性“get”
- php - 如何将类名排除到 phpmd、cleancode ruelset?
- javascript - 在启动画面上反应原生应用程序 firebase 崩溃报告
- c++ - 使用 IOCP 的优雅套接字关闭
- express - Mongoose Schema RESTfull API 和 getone