Aditi M
Aditi M

Reputation: 35

Trying to read and write a JSON file without using an external library or module in C++

I want to read a JSON file without using an external library or module. When I'm trying to do that in the simple fashion (like reading/writing a .txt file), it doesn't read anything from the file.I want to read it line by line as a string, make some changes and replace the line. (Or just write into a new JSON file and use that).

What I want to do is to replace all instances of a char ("≠") with a simple hyphen("-")

What I have tried:

fs.open ("/Users/aditimalladi/CLionProjects/file/JSON_FILE");
string str;
while(getline(fs,str))
{       
    size_t index = 0;

while(true) {

    index = str.find("≠", index);
    if (index == std::string::npos) break;
    str.replace(index, 3, "-");
    index += 1;

}

How do I go about doing this? I know it is easier with jsoncpp and other similar modules. But I would like to do it without.

In the above code the entire file is being read and the character is not being replaced.

Upvotes: 1

Views: 3143

Answers (1)

Pharap
Pharap

Reputation: 4082

Try adjusting your code to (requires C++11):

fs.open ("/Users/aditimalladi/CLionProjects/file/JSON_FILE");
string str;
while(getline(fs,str))
{       
    size_t index = 0;

while(true) {

    index = str.find(u8"≠", index);
    if (index == std::string::npos) break;
    str.replace(index, 3, 1, '-');
    index += 1;

}

Or to keep your source code encoded in ascii, try:

fs.open ("/Users/aditimalladi/CLionProjects/file/JSON_FILE");
string str;
while(getline(fs,str))
{       
    size_t index = 0;

while(true) {

    index = str.find(u8"\u2260", index);
    if (index == std::string::npos) break;
    str.replace(index, 3, 1, '-');
    index += 1;

}

Or for pre C++11 or stdlibs without u8-prefixed literals:

fs.open ("/Users/aditimalladi/CLionProjects/file/JSON_FILE");
string str;
while(getline(fs,str))
{       
    size_t index = 0;

while(true) {

    index = str.find("\xE2\x89\xA0", index);
    if (index == std::string::npos) break;
    str.replace(index, 3, 1, '-');
    index += 1;

}

Upvotes: 2

Related Questions