c++ - 为什么我的 C++ 代码只从输入文件中读取一行?

标签 c++

考虑以下几点:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int score;
    char grade;
    ofstream myfileo;
    ifstream myfilei;
    myfilei.open ("example.txt");
    while (!myfilei.eof()) {
        myfilei >> score;

        cout << "Enter your score:" << endl;
        if (score >= 90)
            grade = 'A';
        else if (score >= 80)
            grade = 'B';
        else if (score >= 70)
            grade = 'C';
        else if (score >= 60)
            grade = 'D';
        else
            grade = 'F';
        cout << "Your grade was a" << grade << endl;
        switch (grade) {
            case 'A': case 'B':
                cout << "Good job" << endl;
                break;

            case 'C':
                cout << "Fair job" << endl;
                break;

            case 'F': case 'D':
                cout << "Failure" << endl;
                break;

            default:
                cout << "invalid" << endl;
        }
    }
    myfilei.close();
    myfileo.close();
    return 0;
    system ("PAUSE");
}

此代码仅从 examples.txt 文件中读取最后一行,该文件充满了格式如下的“分数”:

95
21
41
78
91

为什么上面的代码没有读入并输出所有行?


现在编辑。这只是一个无限循环。

最佳答案

在您的 while 循环中,您不断地覆盖“score”,因此它永远只是文本文件中的最后一个值。如果您需要文件中的多个值,最好使用数组(或类似数组)并将它们添加到其中。

关于c++ - 为什么我的 C++ 代码只从输入文件中读取一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650790/

相关文章:

c++ - "duplicate symbol _heating_unit in BangBangControlTest.o and BangBangControl.o"是什么意思?

c++ - 如何从 const char * 类型字符串中删除换行符

c++ - std::vector 在设置大小时性能较低?

c++ - vector 迭代器 < 或 !=

c++ - 在关闭文件时获取段错误

c++ - 变量或字段 'nameOfVariable' 声明无效不知道为什么 :(

c++ - 不寻常的变量声明

c++ - 二叉搜索树中的有序遍历复杂性(使用迭代器)?

c++ - Boost C++ - 入口点?

c++ - 如何将分隔的 txt 文件传递​​给采用常量 char * 的函数?