JSONCPP无法正确读取文件

Yel*_*ats 12 c++ json

所以我最近安装了JSONCPP,出于某种原因,当我尝试这段代码时它给了我错误:

#include <json.h>
#include <iostream>
#include <fstream>

int main(){
    bool alive = true;
    while (alive){
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::string test = "testis.json";
    bool parsingSuccessful = reader.parse( test, root, false );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << reader.getFormatedErrorMessages()
               << "\n";
    }

    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    alive = false;


    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是文件:

{
"encoding" : "lab"
}
Run Code Online (Sandbox Code Playgroud)

它表示第1行,第1列存在语法错误,并且必须存在值,对象或数组.有人知道怎么修这个东西吗?

编辑:从pastebin更改为当前代码

Mat*_*hen 28

请参阅Json::Reader::parse文档.对于该重载,字符串需要是实际文档,而不是文件名.

您可以使用istream的过载ifstream替代.

std::ifstream test("testis.json", std::ifstream::binary);
Run Code Online (Sandbox Code Playgroud)

编辑:我得到它的工作:

#include "json/json.h"
#include <iostream>
#include <fstream>

int main(){
    bool alive = true;
    while (alive){
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::ifstream test("testis.json", std::ifstream::binary);
    bool parsingSuccessful = reader.parse( test, root, false );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << reader.getFormatedErrorMessages()
               << "\n";
    }

    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    alive = false;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)