gpt4 book ai didi

c++ - 尝试在不使用 C++ 中的外部库或模块的情况下读取和写入 JSON 文件

转载 作者:行者123 更新时间:2023-11-28 01:38:28 24 4
gpt4 key购买 nike

我想在不使用外部库或模块的情况下读取 JSON 文件。当我尝试以简单的方式(如读/写 .txt 文件)执行此操作时,它不会从文件中读取任何内容。我想将其作为字符串逐行读取,进行一些更改并替换线。 (或者只是写入一个新的 JSON 文件并使用它)。

我想做的是用一个简单的连字符(“-”)替换所有字符实例(“≠”)

我尝试过的:

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 或标准库:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com