gpt4 book ai didi

c++ - 将临时变量写入 Json : I get\u0000

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:14 26 4
gpt4 key购买 nike

我面临一个奇怪的问题:当我尝试在 for 循环中添加一个 Json 变量时,它没有正确写入输出文件,而它在循环外运行良好(rapidJson v0.11)。

编辑:循环不是问题,但即使只有括号也会出现错误

这是我的代码示例:

rapidjson::Document output;
output.SetObject();
rapidjson::Document::AllocatorType& allocator = output.GetAllocator();

{
std::string s1("test");
output.AddMember("test_field",s1.c_str(), allocator);
}
std::string s2("test");
output.AddMember("test_field2",s2.c_str(), allocator);

rapidjson::FileStream f(stdout);
rapidjson::PrettyWriter<rapidjson::FileStream> writer(f);
output.Accept(writer);

我得到的输出是:

{"test_field": "\u0000est", 
"test_field2": "test"}

所以括号内添加的变量似乎有问题..你知道它从哪里来吗?

最佳答案

下面的调用:

output.AddMember("test_field",s1.c_str(), allocator);

将第二个参数视为常量字符串。这是不行的,因为 s1 将被销毁出 block 。

您需要复制该字符串。一个解决方案是:

Value v(s1.c_str(), allocator);
output.AddMember("test_field", v, allocator);

或等效地:

output.AddMember("test_field", Value(s1.c_str(), allocator).Move(), allocator);

更快(也更好)的版本是:

output.AddMember("test_field", Value(s1.c_str(), s1.size(), allocator).Move(), allocator);

因为这不需要调用类似strlen() 的函数来查找s1 的长度。并且它可以处理字符串中的空字符。

关于c++ - 将临时变量写入 Json : I get\u0000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647242/

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