首页 > 解决方案 > 当我写入 json 文件时,如何使我的 JsonFormat 不会与 JsonCPP 出错?

问题描述

我正在构建一个 quizbowl 跟踪器来跟踪不同的事实和定义,但我的 JSON 格式无法正常工作。当我尝试它时,json文件抛出错误,我不知道如何修复它。那么,有谁知道如何解决这个问题?

所以我希望我的 json 文件看起来像这样

{
    "sasa": "sasa\n",
    "lol": "saasasa",
    "smth" :  "lolqsas"
}

但它这样做......

{
}{
    "sasa" : "sasa\n"
}

并说只有一个顶级项目是用于 JSON 的,所以我如何将它重新更改为我想要的样子?

这是我的代码

#include <iostream>
#include<fstream>
#include<string>
#include<json/writer.h>
#include <json/json.h>

using std::cout;
using std::cin;
using std::string;

class quiz_bowl
{
public:
    quiz_bowl() 
    {
        cout << "Quizbowl facts and stuff\n";
    }

    static void qb_file_add(std::ofstream& qb_file)
    {

        Json::Value event;
        string term, fact, multifacts;
        cout << "what term" << std::endl;
        cin.ignore();
        std::getline(cin, term);
        cout << "what are the facts?" << std::endl;
        int counter = 0;
        while (std::getline(cin, fact) && !fact.empty())
        {
            if (fact == "stop" && counter != 0)
                break;
            else if (fact == "stop" && counter == 0)
                cout << "Do not stop in the first line\n";
            multifacts += fact + '\n';
            counter++;
        }
        event[term] = multifacts;

        qb_file << event;
        cout << "The term " << term << " has been added\n";
    }


};



int main()
{
    cout << "say add to add something or view to view something\n";
    string answer;
    cin >> answer;
    std::ofstream quiz_bowl_file("qb_facts.json", std::ios::app);

    if (answer == "view")
        cout << "viewing\n";
    else if (answer == "add")
        quiz_bowl::qb_file_add(quiz_bowl_file);
    else
        cout << "Invalid argument passed\n";

}

那么我将如何使格式与 JSON 文件一起使用,而不是通过说出最重要的项目消息来出错

标签: c++jsonc++11jsoncpp

解决方案


推荐阅读