C ++ eof控制while循环错误

时间:2018-02-03 16:23:28

标签: c++

该程序从包含学生的数据文件名中读取数据 名称和他们的测试核心,然后输出每个学生的名字和测试 得分后跟等级。该程序还输出平均测试 为所有学生打分。

inData.txt文件

{
    John Gill 76
    Rina Aora 87
    Steve Brown 89
    Richard Mann 77
}

我将while(inData)更改为while(!inData.eof())之后的问题 最后一行数据(Richard Mann 77)没有显示,平均值不包括它,但while(inData)工作正常。

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int main()
{

    ifstream inData;
    ofstream outData;

    string firstname, lastname;
    double testscore, average, sum = 0;
    char grade = ' ';
    int count = 0 ; 

    inData.open("test.txt");
    outData.open("output.txt");

    inData >> firstname >> lastname >> testscore;

    **while (!inData.eof())** 
    {
        sum += testscore;
        count++;

        while (testscore <= 0 && testscore >= 100)
        {
            cout << "Invalid Testscore" << endl;
            cout << "Please enter again" << endl;
        }

        if (testscore >= 90)
            grade = 'A';
        else if (testscore >= 80)
            grade = 'B';
        else if (testscore >= 70)
            grade = 'C';
        else if (testscore >= 60)
            grade = 'D';
        else grade = 'F';


        outData << setprecision(2) << fixed;

        cout << left << setw(20) << firstname
            << left << setw(20) << lastname << right
            << setw(4) << testscore << setw(2) << grade
            << endl;

        outData << left << setw(20) << firstname
            << left << setw(20) << lastname << right
            << setw(4) << testscore << setw(2) << grade
            << endl;

        inData >> firstname >> lastname >> testscore; 

    }

    outData << endl;

    if (count != 0)
        outData << "Average: " << sum / count << endl;
    else
        outData << "No Data" << endl;

    inData.close();
    outData.close();

    system("pause");
    return 0;
}


// Question 2: Why the while(input) and while(!input.eof()) are working     
//fine?
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char ch;
ifstream input;
ofstream output;

input.open("input.txt");
output.open("otest.txt");

input.get(ch);

while (!input.eof())
{
    cout << ch;
    output << ch << endl;
    input.get(ch);  
}

system("pause");
return 0;

}

0 个答案:

没有答案