读取文本文件以构建C++

Reading Text files to structure C++

本文关键字:构建 C++ 文件 取文本 读取      更新时间:2023-10-16

我正在使用结构,但我不知道如何从文本文件添加信息。这是我的基本结构。我正在为我的结构添加年龄和名称。

 using namespace std;
struct stud1
{
    int age;
    char name[20];
};
int main()
{

    stud1 stud =
    {
        9,
        "Lee"
    };
cout<< stud.name <<endl;
}

在代码的末尾,Lee将被打印出来。我想添加信息,但来自文本文件。如何将文本文件的第一行添加到结构中?

这是文本文件:

10 John
12 Tim
11 Jack

首先,根据 SO 规则,您应该在提问时提供 MCVE。其次,您应该避免using namespace std;因为它打开了全局命名空间污染的闸门。为了方便起见,您可以执行诸如using std::cout;之类的操作,而无需打开整个标准命名空间。最后,如果你只是使用std::string而不是char[]在你的struct生活会更容易,但无论如何,这是基本的想法。您可以直接从输入文件中读取年龄和名称到局部变量中,然后根据这些输入值设置结构元素。这是假设输入文件的每一行都像您所说的那样,并且没有错误检查。

#include <fstream>  // for std::ifstream
#include <string>   // for std::string
#include <cstring>  // for strcpy()
std::ifstream infile("garbage.txt");
if (infile.is_open())
{
    int age;
    std::string namestr;
    while (infile >> age >> namestr)
    {
        stud1 temp;
        temp.age = age;
        strcpy( temp.name, namestr.c_str() );
        // do whatever before struct goes out of scope
    }
    infile.close();
}