My project should read a json file but generate a error - c++

i have made a example for try the JsonCpp library.
I have included it in my project, the project content is this:
#include <cstdlib>
#include <string>
#include <fstream>
#include <iostream>
#include <json\value.h>
#include <json\json.h>
using namespace std;
int main()
{
Json::Reader reader; //for reading the data
Json::Value newValue; //for modifying and storing new values
Json::StyledStreamWriter writer; //for writing in json files
//opening file using fstream
ifstream file("items.json");
// check if there is any error is getting data from the json file
if (!reader.parse(file, newValue)) {
cout << reader.getFormattedErrorMessages();
exit(1);
}
cout << newValue["Category"] << endl;
file.close();
system("pause");
}
The json file name is items.json and its content is this:
{
"Category" : "Technical",
"Date" : "1 January 2021",
"Name" : "Java2Blog",
"first" : "Shishank",
"last" : "Jain"
}
But when i compile and run the project, it generate this error:
* Line 1, Column 1
Syntax error: value, object or array expected.
I have followed this guide: https://java2blog.com/json-parser-cpp/
this is my first time using json in a C ++ project

I have solved my problem.
The json file was already encoded in UTF-8, and the file path was correct.
I have changed my code like this:
#include <fstream>
#include <iostream>
#include <json\json.h>
using namespace std;
int main()
{
ifstream file;
file.open("items.json");
if (!file)
{
cout << "File non esiste" << endl;
}
else
{
Json::Reader reader; //for reading the data
Json::Value value; //for modifying and storing new values
reader.parse(file, value);
cout << value["Category"] << endl;
}
file.close();
system("pause");
}
I apologize to everyone for the inconvenience

Related

write a script in c++ which read a CSV file( fail to open it)

i'm trying to write a script in c++ which read a CSV file so i can treat it later .i ve used fstram but the file always fail to open**
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string filename = "hello.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
cout<<"khalil"<<endl;
string scores[32];
string names[32];
int iter = 0;
while (iter <= 5)
{
fin >> names[iter] >> scores[iter];
cout << iter <<"\n";
cout<<names[iter]<< "\n";
cout<<scores[iter]<<"\n";
iter++;
}
fin.close();
}
Try using a fully qualified path name, e.g.:
string filename = "C:\\Documents\\hello.txt";It appears your program isn't opening the file because it can't find it.
You can use QFile class to do this operation.
#include <QFile>
#include <QStringList>
#include <QDebug>
int main()
{
QFile file("C\\hello.txt");
if (!file.open(QIODevice::ReadOnly)) {
qDebug()<<file.errorString();
return 0;
}
QStringList firstList, secondList;
while (!file.atEnd()) {
QByteArray line = file.readLine();
firstList.append(line.split(',')[0]);
secondList.append(line.split(',')[1]);
}
qDebug()<<firstList;
qDebug()<<secondList;
}

Problem with file by using fstream library and print on screen?

I am trying to print the data located in the weapon.obj file, but it's not working.
Compiler Error: error: no matching function for call to
'getline(std::ifstream&)'|
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while (getline(execute_weapon_OBJ))
{
cout << execute_weapon_OBJ << '\n';
}
execute_weapon_OBJ.close();
}
You must specify where to read the data and use that for printing.
#include <iostream>
#include <fstream>
#include <string> // add this to use std::string
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
string weapon; // add this for read buffer
while (getline(execute_weapon_OBJ, weapon)) // add where to read
{
cout << weapon << '\n'; // print what was read instead of the stream
}
execute_weapon_OBJ.close();
}
May be this is the solution you are looking for
You need a variable to store the line read from the file and you need to print the variable not the variable used to initialize the file stream.
The error is in the while loop[The new code is below]
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while(getline(execute_weapon_OBJ,line))
{
cout << line << '\n';
}
execute_weapon_OBJ.close();
}

opening an ifstream file in C++

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file;
file.open ("ernio.txt", ios::in);
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
It prints example instead of reading line by line from the file. What am I doing wrong?!? (the file is in the exact same place as the main.cpp) We even tried:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file("ernio.txt");
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
Please help
The file needs to be in the directory from where the executable will be called, not in the source directory where your main.cpp resides.
When you build small programs with gcc or something similar from the command line, often the executable is in the current working directory, where the compiler will also draw the source files from.
When using a build system or an IDE, however, then usually the target of a build is different from that where the sources reside.

After convert string to const *json, when pasing json object, shows failed: (IsObject()), how to solve this?

After convert string strjson to const char* json, when interate, shows
failed: (IsObject()), function FindMember,failed, I don't understand why showed this, I think this the json object is correct format.
//
// main.cpp
// rapid
//
// Created by Shi Yan on 10/7/17.
// Copyright © 2017 Shi Yan. All rights reserved.
//
#include <iostream>
#include "rapidjson.h"
#include "document.h"
#include <fstream>
using namespace std;
using namespace rapidjson;
void readjson(){
ifstream handle("meta_Books.json");
if(handle.is_open()){
//cout<<"open success"<<endl;
const char* json;
string strjson;
int i=1;
while(getline(handle,strjson)){
if(i>4)
break;
cout<<strjson<<endl;
cout<<strjson.length()<<endl;
i++;
json=strjson.c_str();
cout<<"*********************"<<endl;
cout<<*json<<endl;
StringStream s (json);
Document document;
document.ParseStream(s);
Value::ConstMemberIterator itr = document.FindMember("asin");
cout<<itr->name.GetString()<<" = "<< itr->value.GetString()<<endl;
}
}
}
int main() {
readjson();
return 0;
}
I think the format of json object , so why failed?
As you can see , the getline() method works well, because the output of string is an complete string
The assertion error means that FindMember() is being called on a Value that does not represent a JSON object (IsObject() is false).
Since there is only 1 FindMember() in the code you showed, that implies that document.IsObject() is false when document.FindMember() fails. Either the JSON you are parsing does not start with an object in its root, or the parse failed. Neither condition of which you are testing for in your code.
If I had to guess (and please don't make people guess!), the failing JSON document likely contains an unencoded line break in it (that is not illegal inside of JSON string values). That would cause std::getline() to exit prematurely, thus causing parsing issues.
The 1st screenshot you showed supports that conclusion, showing that strjson is being split between 2 separate "lines" when the error occurs.
Rather than using std::getline() to read the file line-by-line, risking errors on embedded line breaks, I suggest you try using RapidJSON's BasicIStreamWrapper class to read the file document-by-document instead. ParseStream() has a kParseStopWhenDoneFlag flag that allows parsing multiple root documents from a single input stream:
kParseStopWhenDoneFlag 
After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error.
For example:
#include <iostream>
#include <fstream>
#include "rapidjson.h"
#include "document.h"
#include "istreamwrapper.h"
using namespace std;
using namespace rapidjson;
void readjson()
{
ifstream handle("meta_Books.json");
if (!handle.is_open())
{
// handle error...
cout << "error opening file" << endl;
}
else
{
BasicIStreamWrapper<ifstream> s(handle);
for(int i = 1; i <= 4; ++i)
{
Document document;
ParseResult pr = document.ParseStream<kParseStopWhenDoneFlag>(s);
if (!pr)
{
// handle error...
cout << "error parsing document " << i << endl;
}
else if (!document.IsObject())
{
cout << "document " << i << " is not an object" << endl;
}
else
{
Value::ConstMemberIterator itr = document.FindMember("asin");
if (itr != document.MemberEnd())
cout << "asin = " << itr->value.GetString() << endl;
else
cout << "asin not found" << endl;
}
}
}
}
int main()
{
readjson();
return 0;
}

Read multiple files with C++

I would like to edit the below code to look at and read several other files in the proc directory. May I get some guidance on how to improve this code to look at other proc files other than just the uptime. Thank you.
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()
int main()
{
using namespace std;
// ifstream is used for reading files
// We'll read from a file called Sample.dat
ifstream inf("/proc/uptime");
// If we couldn't open the input file stream for reading
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, file could not be opened for reading!" << endl;
exit(1);
}
// While there's still stuff left to read
while (inf)
{
// read stuff from the file into a string and print it
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}
return 0;
// When inf goes out of scope, the ifstream
// destructor will close the file
}
Here it is written with a function instead
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()
using namespace std;
void readfile(string file)
{
ifstream inf (file.c_str());
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, file could not be opened for reading!" << endl;
exit(1);
}
while (inf)
{
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}
}
int main()
{
cout << "-------------------obtaining Totaltime and Idletime----------------" << endl;
readfile("/proc/uptime");
return 0;
}