下午好!我有一个静态方法listOfStudents()
可以打开一个文本文件并从那里读取我的数据......
我的文本文件如下所示:
正如您在图片中看到的,一个带有数据的简单文本文件。
我的任务是从那里获取名字和姓氏并将其显示在屏幕上:
我的完整方法如下所示:
static void listStudents(){
cout << endl << "List students" << endl<< endl;
ifstream textfile;
string line;
string unused = "";
textfile.open("students.txt");
if(textfile.is_open()){
int count = 0;
for(int i = 0 , j = 0; !textfile.eof(); i++){
if(i == j){
count++;
textfile >> line;
cout << count << ": " << line;
textfile >> line;
cout << " " << line << endl;
j+=11;
}else{
textfile >> unused;
unused = "";
}
}
}else{
cout << "You don't have any students!" << endl;
}
textfile.close();
cout << endl << endl;
main();
}
我在一个文本文件中有 4 个学生,当我显示以下内容时:
如您所见,一切都很好,只是在最后,出于某种原因,它生成了另外 1 行,其中前一个学生的姓氏重复了两次。
问: 他为什么要这样做?如何纠正?
因为不需要检查
在检查时,尚未到达文件末尾 - 只有在尝试读取时才到达。因此,无法读取任何内容,并且先前的值存储在变量中。并且仅在循环的下一次迭代之前执行下一次检查。