C++使用file.eof()读取学生记录文件出现无限循环如何解决
问题根因
eof()的触发逻辑不符合预期:只有读取操作尝试读取超出文件末尾的内容失败后,eof()才会返回true,而非文件指针到达末尾就立刻置位。如果文件末尾存在格式不匹配的内容、文件损坏,读取操作会触发流的fail标志,但eof()始终返回false,你没有判断流的有效状态,就会进入无限循环,反复输出最后一次成功读取的内容。- 无数据判断逻辑存在漏洞:
total初始值为1,就算没有读到任何学生数据,total也不可能等于0,无数据时的提示语句永远不会执行。
修复方案
直接将读取操作作为while的判断条件即可,ifstream的流提取运算符>>会返回流对象本身,放在条件判断中会自动转换为布尔值:读取成功返回true,读取失败(包含到达文件末尾、格式错误等所有情况)返回false,直接退出循环。同时修正无数据判断的逻辑漏洞。
修复后代码如下:
//Displaying Students Record Table void Student::display() { system("cls"); ifstream file; int total = 0; // 初始值改为0,适配无数据判断逻辑 int x; cout << "\n-----------------------------Students Record Table-----------------------------" << endl; file.open("studentRecord.txt"); if (!file) { cout << "\n\t\t\tNo Data Is Present."; file.close(); } else { // 直接将读取操作放在while判断条件中,自动判断读取是否成功 while(file >> name >> roll >> year >> group >> course >> adress >> email >> contact >> grade) { total++; cout << "\n\n\t\t\t Student Consecutive Number: " << total << endl; cout << "\t\t\t Student's Name: " << name << endl; cout << "\t\t\t Student's ID Number: " << roll << endl; cout << "\t\t\t Student's Year: " << year << endl; cout << "\t\t\t Student's Group: " << group << endl; cout << "\t\t\t Student's Course: " << course << endl; cout << "\t\t\t Student's Adress: " << adress << endl; cout << "\t\t\t Student's Email: " << email << endl; cout << "\t\t\t Student's Contact: " << contact << endl; cout << "\t\t\t Student's Final Grade: " << grade << endl; } if (total == 0) { cout << "\n\t\t\tNo Data Is Present."; } } do { cout << "\n\t\t\t If You Want to Back at previous page press 0 and Enter: "; cin >> x; if (x == 0) { file.close(); } } while (x != 0); }
内容的提问来源于stack exchange,提问作者Jacob
相关产品推荐
相关产品推荐

