首页 > 解决方案 > 在 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"){}

这些都没有奏效。

标签: c++stringnull

解决方案


问题是响应可能包含空格。因此,将其与 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";}

推荐阅读