C++如何从文件中读取我想要的内容

C++ how to read what I want from a file?

本文关键字:我想要 读取 文件 C++      更新时间:2023-10-16

例如,如何从结构化.txt文件中为C++代码中的变量赋值?如果我有以下input.txt的结构如下:

    <Name> "John Washington"
    <Age> "24"
    <ID> "19702408447417"
    <Alive Status> "Deceased"

在我的c++代码中,如果我有

ifstream read("input.txt",ios::in);
char name[64];
read>>name;//name will point to John Washington string
int age;
read>>age;// cout<<age will return 24;
int ID;
read>>ID;// cout<<ID will return 19702408447417
char Alivestatus[32];
read>>Alivestatus;//Alivestatus will point to Deceased string;

我怎样才能使它像上面那样工作?

As@πάῥεῖ在注释中提到,您将需要实现一个解析器,该解析器可以解释文件中的<>标记。此外,我建议重新考虑数据类型。

具体来说,考虑到您使用char []没有特殊原因,请切换到std::string。我不知道你的代码的用例,但如果input.txt碰巧包含的数据大于数组的大小,或者更糟的是,如果输入是用户控制的,这很容易导致缓冲区溢出和不必要的漏洞利用。std::string还具有标准化、优化的优点,比char数组友好得多,并且具有各种有用的算法和功能,可随时使用。

关于文本文件解析,您也许可以实现以下内容:

    #include <fstream>
    #include <iostream>
    #include <string>
    int main()
    {
        std::ifstream input_file("input.txt");
        std::string name_delimeter("<Name> ");
        std::string age_delimeter("<Age> ");
        std::string id_delimeter("<ID> ");
        std::string alive_delimeter("<Alive Status> ");

        std::string line;
        std::getline(input_file,line);
        std::string name(line,line.find(name_delimeter) + name_delimeter.size()); // string for the reasons described above
        std::getline(input_file,line);
        int age = std::atoi(line.substr(line.find(age_delimeter) + age_delimeter.size()).c_str());
        std::getline(input_file,line);
        std::string id(line,line.find(id_delimeter) + id_delimeter.size()); // the example ID overflows 32-bit integer
                                                                            // maybe representing is a string is more appropriate
        std::getline(input_file,line);
        std::string alive_status(line,line.find(alive_delimeter) + alive_delimeter.size()); // string for the same reason as name

        std::cout << "Name = " << name << std::endl << "Age = " << age << std::endl << "ID = " << id << std::endl << "Alive? " << alive_status << std::endl;
    }

代码的基础只是读取文件的结构,并从中构造适当的数据类型。事实上,因为我在大多数数据类型中都使用了std::string,所以通过std::字符串的构造函数和可用函数可以很容易地构建正确的输出。

也许您是在循环中执行此操作,或者文件有几个结构。为了解决这个问题,您可以创建一个Record类,该类重载operator >>并根据需要读入数据。