c++ - 在 C++ 中逐字读取 .txt 文件到结构体

标签 c++ string file-io input vector

我在 CMPT 类(class)的实验室作业中遇到了一些问题... 我正在尝试读取一个文本文件,该文件每行包含两个单词和一串数字,并且该文件可以与任何人制作的一样长。

一个例子是

Xiao Wang 135798642
Lucie Chan 122344566
Rich Morlan 123456789
Amir Khan 975312468
Pierre Guertin 533665789
Marie Tye 987654321

我必须使每一行成为一个单独的“学生”,所以我正在考虑使用结构来做到这一点,但我不知道如何做到这一点,因为我需要将第一个、最后一个和ID号分开.

struct Student{
    string firstName;
    string secondName;
    string idNumber;
};

所有单独读取每个单词的尝试都失败了(最终读取了整行),我感到有点沮丧。

在@Sylence的帮助下,我成功地分别阅读了每一行。不过,我仍然对如何用空格分割行感到困惑。 ifstream中有split函数吗? Sylence,“parts”是一个数组吗?我看到你在 [] 中有索引。 students.add(stud) 到底是做什么的? 到目前为止我的代码是:

int getFileInfo()
{
    Student stdnt;
    ifstream stdntFile;
    string fileName;
    char buffer[256];
    cout<<"Please enter the filename of the file";
    cin>>filename;
    stdntFile.open(fileName.c_str());
    while(!stdFile.eof())
    {
        stdFile.getLine(buffer,100);
    }
    return 0;
}

这是我修改后的 getFileInfo() 的最终版本,谢谢 Shahbaz,提供了读取数据的简单快捷的方法。

void getFileInfo()
{
    int failed=0;
    ifstream fin;
    string fileName;
    vector<Student> students; // A place to store the list of students

Student s;                  // A place to store data of one student
cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
do{
    if(failed>=1)
        cout<<"Please enter a correct filename."<<endl;
    cin>>fileName;
fin.open(fileName.c_str());// Open the file
failed++;
}while(!fin.good());
while (fin >> s.firstName >> s.lastName >> s.stdNumber)
    students.push_back(s);
fin.close();
cout<<students.max_size()<<endl<< students.size()<<endl<<students.capacity()<<endl;


return;
}

我现在困惑的是如何访问输入的数据!我知道它被放入 vector 中,但是如何访问 vector 中的各个空间,以及输入的数据到底如何存储在 vector 中?如果我尝试计算 vector 的一个点,则会收到错误,因为 Visual Studio 不知道要输出什么(我猜)。

最佳答案

其他答案都很好,但看起来有点复杂。您可以简单地通过以下方式完成:

vector<Student> students;   // A place to store the list of students

Student s;                  // A place to store data of one student

ifstream fin("filename");   // Open the file

while (fin >> s.firstName >> s.secondName >> s.idNumber)
    students.push_back(s);

请注意,如果 istream 失败,例如文件完成时,istream 对象 (fin) 将计算为 false 。因此 while (fin >> ....) 将在文件完成时停止。

附注不要忘记检查文件是否打开。

关于c++ - 在 C++ 中逐字读取 .txt 文件到结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947851/

相关文章:

c++ - 正在检查大型订购 list 中的成员资格?

c++ - 自定义数据结构的迭代器

php - 将此字符串转换为日期格式以保存到 mysql

javascript - JS 中的正则表达式

file-io - headless (headless)运行 Metro 应用程序

c++ - 我的 API 应该使用非成员函数来作用于对象,还是使函数成为对象的公共(public)函数?

c++ - 如何在 Boost Dijkstra 中定义自定义距离?

arrays - 如何从带有链接的数组中获取值?

r - 如何向/从 UTF-8 编码文件写入和读取可打印的 ASCII 字符?

file-io - 在 Fortran 90 中从文件末尾读取