gpt4 book ai didi

c++ - 逐行计算文件 : EOF repeating the last number (can't use breaks)

转载 作者:太空狗 更新时间:2023-10-29 21:44:21 25 4
gpt4 key购买 nike

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

谢谢。

输入文件:

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;
}

最佳答案

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

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);

关于c++ - 逐行计算文件 : EOF repeating the last number (can't use breaks),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com