在 c++ 中读取配置文件 json 并没有停止

Reading configuration file json in c++ didn't stop

本文关键字:并没有 json 配置文件 c++ 读取      更新时间:2023-10-16

喜欢标题,我的代码有一些问题。似乎该程序不会停止。我认为问题是C 无法读取.json文件,因为我已经使用文本文件进行了测试,该程序没有出现错误,然后我使用未检查的文件和程序循环进行测试,就像我使用.json文件测试时一样。因此,我认为C 无法读取不存在的文件,并且似乎有同样的问题。请帮我。我只是开始学习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;
}