从文本文件读取直到 EOF 无限循环

Reading from text file until EOF infinite loop

提问人:Jacob 提问时间:5/12/2021 更新时间:5/12/2021 访问量:190

问:

我正在为我的学校编程项目工作,我想出了“学生经理计划”的想法。

这些: 作为变量存储在名为 的类中。name, roll, year, group, course, adress, email, contact, gradeStudent

学生的数据由用户键盘输入写入,并按对象保存在文件中。 我怎样才能防止这个 while 循环成为一个非无限循环。我找不到这个问题的解决方案。studentRecord.txt

'''

//Displaying Students Record Table
void Student::display() {
    system("cls");
    ifstream file;
    int total = 1;
    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 {
        file >> name >> roll >> year >> group >> course >> adress >> email >> contact >> grade;
        while(!file.eof()) {
            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;
            file >> name >> roll >> year >> group >> course >> adress >> email >> contact >> grade;
        }
        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);
}

'''

C++ While-Loop 无限循环 eof cppcheck

评论

1赞 Scheff's Cat 5/12/2021
这回答了你的问题吗?为什么 iostream::eof 在循环条件(即 'while (!stream.eof())'))中被认为是错误的?
1赞 Scheff's Cat 5/12/2021
如果任何流输入运算符失败,则流将设置为失败状态,并且以下任何输入运算符都不会再读取任何内容。但是,失败状态并不意味着流已到达文件末尾。所以,你就是这样 - 陷入了无限循环。
0赞 Jacob 5/12/2021
@Scheff 很遗憾,不,它没有。
0赞 Jacob 5/12/2021
@Scheff 那我应该改变什么
1赞 Scheff's Cat 5/12/2021
请阅读链接。有多种答案可以解释“为什么不”以及“该怎么做”。;-)

答: 暂无答案