我在 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/