我想在不使用外部库或模块的情况下读取JSON文件。当我尝试以简单的方式执行此操作(例如读取/写入.txt文件)时,它不会从文件中读取任何内容,而是要逐行读取它作为字符串,进行一些更改并替换线。 (或者只是写入一个新的JSON文件并使用它)。
我想做的是用一个简单的连字符(“-”)替换char(“≠”)的所有实例
我尝试过的
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;
}
我该怎么做呢?我知道使用jsoncpp和其他类似模块会更容易。但是我想没有它。
在上面的代码中,正在读取整个文件,并且不替换字符。
最佳答案
尝试将代码调整为(需要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;
}
或者,要使您的源代码以ascii编码,请尝试:
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;
}
或对于不带
u8
前缀文字的C ++ 11或stdlibs: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;
}
关于c++ - 尝试在不使用C++中使用外部库或模块的情况下读写JSON文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48335973/