逐行计算文件:重复最后一个数字(可以'使用中断)

时间:2013-11-30 20:23:22

标签: c++ fstream eof

这应该是一个非常简单的程序。我的问题是最后一个数字重复了,我完全理解这一点,因为直到我回到循环内并读取数字时才达到EOF,那时,为时已晚。在for循环中输入“fileIn>> num”之后,我可以通过执行类似“If(!fileIn)break; count ++”之类的操作来解决这个问题(如果(count> 1),我会进入计算平均值,输出总数,平均值等的最后一段代码。唯一的问题是我的教授不希望在这个程序中休息,所以我只是想看看如何解决它。

感谢。

输入文件:

346 130 982 90 656 117 595

415 948 126 4 558 571 87

42 360 412 721 463 47 119

441 190 985 214 509 2 571

77 81 681 651 995 93 74

310 9 995 561 92 14 288

466 664 892 8 766 34 639

151 64 98 813 67 834 369

#include <iostream>
#include <fstream>

using namespace std;

const int NumPerLine = 7;

int main()
{

int num = 0;
int total = 0;
float average = 0;
int min = 0;
int max = 0;

ifstream fileIn;

fileIn.open("File2.txt");
ofstream fileOut("Output.txt");

if (!fileIn) {

cout << "/nError opening file...Closing program. n";
exit(1);
}

while (fileIn) {

cout << endl;

int total = 0;
int count = 0;

for (int k = 0; k < NumPerLine; k++) {

    fileIn >> num;

    if (k == 0) {
    max = num;
    min = num;
    }

    total += num;
    cout << num << " ";
    fileOut << num << " ";

    if (num > max)
    max = num;

    if (num < min)
    min = num;

}

average = total / NumPerLine;

cout << "/n/nTotal is " << total << "." << endl;
cout << "Average is " << average << "." << endl;
cout << "Lowest number is " << min << endl;
cout << "Largest number is " << max << endl;

fileOut << "/n/nTotal is " << total << "." << endl;
fileOut << "Average is " << average << "." << endl;
fileOut << "Lowest number is " << min << endl;
fileOut << "Largest number is " << max << endl << endl;
}


fileIn.close();
fileOut.close();

cout << "/nData has been processed, and copied to the file, " Output.txt "." << endl << endl;

return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以使用do/while(特别是因为初始非NULL检查)而不是使用while循环:

do {

cout << endl;

int total = 0;
int count = 0;

for (int k = 0; k < NumPerLine; k++) {

    fileIn >> num;

    if (k == 0) {
    max = num;
    min = num;
    }

    total += num;
    cout << num << " ";
    fileOut << num << " ";

    if (num > max)
    max = num;

    if (num < min)
    min = num;

} while(fileIn);

答案 1 :(得分:1)

在尝试读取之后,始终检查流的状态:如果输入失败,则流进入故障模式(即std::ios_base::failbit已设置)并且流转换为false