Reputation: 35
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
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