c++ - 在 C++ 中读取配置文件 json 并没有停止
问题描述
就像标题一样,我的代码有一些问题。程序似乎没有停止。我认为问题是 c++ 无法读取 .json 文件,因为我已经用文本文件进行了测试,程序没有出错,然后我用不存在的文件和程序循环进行测试,就像我用 .json 文件测试时一样。所以我认为 c++ 无法读取不存在的文件,并且似乎 .json 也有同样的问题。请帮我。我刚开始学习 c++,所以如果你能解决问题,我希望你能告诉我为什么我的代码是错误的并推荐解决方案。这是我的代码
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
void main()
{
fstream file;
char a[80], b;
string c;
file.open("D://New folder//testcase//Project3//conf.json",ios::in );
while (!file.eof())
{
file.getline(a, 80);
cout << a << "\n";
}
if (file.fail()) cout << "Abc";
file.close();
cin >> b;
}
这是我的配置文件
{
"name": "PF182-A01",
"version": "1.0.0",
"author": "Duc Dung Nguyen",
"email": "nddung (at) hcmut.edu.vn",
"WelcomeText": {
"line1": "******************************************************************************",
"line2": "* Welcome to CSE-HealthCare System *",
"line3": "* This is a simple application designed for the first assignment of PF *",
"line4": "* course (CO1011, Semester 182). The student must demonstrate the ability to *",
"line5": "* write a program for a given problem. The student need to analyze the *",
"line6": "* requirements of the problem before implementing the application. *",
"line7": "******************************************************************************",
"line8": "Email: nddung@hcmut.edu.vn",
"line9": "(c) 2019 Duc Dung Nguyen All Rights Reserved."
},
"Menu": {
"opt1": "Introduction",
"opt2": "Login",
"opt3": "Registration",
"opt4": "Help",
"opt5": "Exit"
},
"IntroTime": 3,
}
解决方案
文件名不正确
file.open("D://New folder//testcase//Project3//conf.json",ios::in );
它应该是
file.open("D:/New folder/testcase/Project3/conf.json",ios::in );
或者
file.open("D:\\New folder\\testcase\\Project3\\conf.json",ios::in );
而while循环不正确
while (!file.eof())
{
file.getline(a, 80);
cout << a << "\n";
}
它应该是
while (file.getline(a, 80))
{
cout << a << "\n";
}
见这里为什么循环条件内的 iostream::eof 被认为是错误的?
最后,检查文件打开是否成功总是一个好主意
file.open("D:/New folder/testcase/Project3/conf.json",ios::in );
if (!file.is_open())
{
cout << "can't open file !!!\n";
return 0;
}
推荐阅读
- reactjs - 如何在 React-Bootstrap 中实现下拉动画?
- c# - 预制空 Unity C#
- python - 从 vscode 中的目录运行 .py 和文件
- visual-studio - Visual Studio 搜索/替换为本地函数名称
- python - 为什么每次使用 reshape 多次调用张量都会改变其值
- python - 从 Sphinx 文字中排除注释包括
- javascript - 在选择框的更改选项上动态创建 Javascript 映射对象
- java - 使用 Java 从 Apache Phoenix 获取记录时响应缓慢
- sql - SQL - 根据一组 CASE 语句将多行合并为一个
- laravel-5 - 单击时引导按钮不路由