0

I got JSON written in String. The length in Notepad++ shows 210 characters, but in C+++ only 182.

How do I get 210 characters in C++?

Example JSON with Escape quotes:

{\"_id\":\"5de2dff0d6c9e312d659bc42\",\"index\":\"0\",\"guid\":\"eba0e936-0b18-48ec-88ca-00312ede4a7d\",\"isActive\":\"false\",\"balance\":\"$1,636.50\",\"picture\":\"http://placehold.it/32x32\",\"age\":\"36\"}

And my code:

#include <iostream>

using namespace std;

int main()
{
    //210 characters
    string str = "{\"_id\":\"5de2dff0d6c9e312d659bc42\",\"index\":\"0\",\"guid\":\"eba0e936-0b18-48ec-88ca-00312ede4a7d\",\"isActive\":\"false\",\"balance\":\"$1,636.50\",\"picture\":\"http://placehold.it/32x32\",\"age\":\"36\"}";
    cout << "String Length = " << str.length(); // return 182
    return 0;
}
ruohola
  • 21,987
  • 6
  • 62
  • 97
Leon M
  • 3
  • 3
  • 4
    Pop quiz: `\"` is two characters, according to Notepad. Your pop quiz: how many characters is that, according to C++, when used as part of a quoted string literal, as is the case in your code? Free clue: it's not two characters. – Sam Varshavchik Nov 30 '19 at 21:52
  • How is this related to the ESP 32 Wi-Fi and Bluetooth combo chip? – Thomas Sablik Nov 30 '19 at 21:57

1 Answers1

1

Every \" ends up not being two different characters, but just one " character, that's why the character count seems to be off. The reason for this is that double quotes in a string literal need to be escaped.

You can use a raw string literals to hold this string, because every \ will then just be taken as a literal backslash character in them, and thus every \" will just mean a backslash + a double quote:

#include <iostream>

using namespace std;

int main()
{
    string str = R"({\"_id\":\"5de2dff0d6c9e312d659bc42\",\"index\":\"0\",\"guid\":\"eba0e936-0b18-48ec-88ca-00312ede4a7d\",\"isActive\":\"false\",\"balance\":\"$1,636.50\",\"picture\":\"http://placehold.it/32x32\",\"age\":\"36\"})";
    cout << "String Length = " << str.length();
    return 0;
}

Output:

String Length = 210
ruohola
  • 21,987
  • 6
  • 62
  • 97