c++ - 在 C++ 中检查字符串是否为“null”
问题描述
我知道 std::string 不能为空,但我无法弄清楚这里的问题,让我解释一下。这是我的功能:
void HandleResponse(Mod::PlayerEntry player, std::string response)
所以response
通常有一个json值,我用nlohmann json解析它:
auto value = json::parse(response);
在某些情况下,它给出“null”,我使用以下方法进行调试:
std::cout << "response: " << response << ", value: " << value << std::endl;
// outputs: response: null, value: null
现在的问题是我不知道如何比较它是否为空,这是我尝试过的所有不同检查:
if(response == "null"){}
if(response == ""){}
if(response.empty()){}
if(response == 0){}
if(response == std::string("null")){}
if(response.c_str() == "null"){}
if(response.c_str() == NULL){}
if(response.c_str() == '\0'){}
if(value == "null"){}
这些都没有奏效。
解决方案
问题是响应可能包含空格。因此,将其与 null 进行精确比较可能比您想象的要难。您需要检查是否response
包含null
但其他任何内容都是简单的空白。
但是查看nlohmann
库该json::parse()
函数返回一个类型的对象json
。
json value = json::parse(response);
您可以简单地检查值的类型:
id (value.is_null()) {std::cout << "is null\n";}
id (value.is_boolean()) {std::cout << "is bool\n";}
id (value.is_number()) {std::cout << "is numb\n";}
id (value.is_object()) {std::cout << "is obj\n";}
id (value.is_array()) {std::cout << "is array\n";}
id (value.is_string()) {std::cout << "is string\n";}
推荐阅读
- hyperledger-fabric - 如何计算超级账本结构中的默克尔根?
- jquery - jquery查找文本等于foobar的标签元素
- java - 如何使用 ReflectionAPI 在 Map 上调用“put”方法
- ionic-framework - 单击选项卡按钮时,IONIC 4滚动到顶部
- ios - 使用 show(push) segue 时查看父视图内容
- python - 如何在其他两列上基于 groupby 在 pandas 列中聚合项目二进制文件
- python - 如何将 csv 作为嵌套字典导入?
- python - 神经网络可以学会充当多路复用器吗?
- r - 在 nls 上设置上限适合逻辑增长曲线
- swift - 将 UILabel 的宽度调整为标签中文本的长度