从txt文件C ++读取多行

时间:2017-06-27 13:40:28

标签: c++ loops

来自文件txt。

44 55 77 88
79 88 100 99
77 99 98 99
100 88 89 100
55 56 40 77

我如何逐行阅读添加并获得平均值?这是我到目前为止所做的。

int main()
{

    ifstream numberInputFile;
    int sum = 0.0, average = 0.0;
    int test1, test2, test3, test4;    
    numberInputFile.open("grades.txt");
    if (numberInputFile)
    {
        while (numberInputFile >> test1 >> test2 >> test3 >> test4)
        {
            sum += (test1 + test2 + test3 + test4);

            //find the average

            average = sum / 4;

            if(average >= 90 && average <= 100)
            {
                cout << average << " A" <<endl;
            }
            else if(average >= 80 && average < 90)
            {
                cout << average << " B" <<endl;
            }
            else if(average >= 70 && average < 80)
            {
                cout << average << " C" <<endl;
            }
            else if(average >= 60 && average < 70)
            {
                cout << average << " D" <<endl;
            }
            else if(average < 60)
            {
                cout << average << " F" <<endl;
            }
            else
                numberInputFile.close();
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:-1)

而不是:

if (numberInputFile)
    {}
        while (numberInputFile >> test1 >> test2 >> test3 >> test4)
        {}

尝试:

 string line;
    while(getline(inFile, line))
    { 
     std::istringstream iss(line)
      while(iss >> test)
        {  sum+=test;
            .
            .
            ..
        }
    //Check average here, outside the loop

    }