xBeastMode
xBeastMode

Reputation: 29

Check if string is "null" in C++

I know that std::string cannot be null, but I can't figure out the problem here, let me explain. This is my function:

void HandleResponse(Mod::PlayerEntry player, std::string response)

So response usually has a json value, I parse it with nlohmann json:

auto value = json::parse(response);

In certain occasions, it gives "null", I debugged using:

std::cout << "response: " << response << ", value: " << value << std::endl;
// outputs: response: null, value: null

Now the problem is that I can't figure out how to compare if it's null, here's all the different checks I've tried:

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"){}

None of these have worked.

Upvotes: 1

Views: 9348

Answers (3)

xBeastMode
xBeastMode

Reputation: 29

Apparently the cause is really stupid. I trimmed the string with:

boost::trim(response);

Now I checked if the response is "null":

if (response == "null") return;

and boom, it works!

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264401

The problem is that response can potentially contain white space. So comparing it exactly for null might be harder than you think. You need to check if response contains null but that anything else is simple white space.

But looking at nlohmann library the json::parse() function returns an object of type json.

json value = json::parse(response);

You can simply check the type of the value:

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";}

Upvotes: 4

eerorika
eerorika

Reputation: 238351

If response is a std::string, and inserting it into an output stream produces "null", then a correct way to compare it is response == "null".

Upvotes: 1

Related Questions