【发布时间】:2017-11-15 17:16:47
【问题描述】:
在一个项目中,我需要用数字填充文件并使用 getline 逐行读取这些数字,然后显示每行的总数、平均值、最大值和最小值。除了我的 getline 似乎没有正常工作之外,一切都准备就绪,因为总、平均值等的输出始终为 0。任何帮助都将不胜感激。谢谢!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream myfile;
myfile.open("file.txt");
if(!myfile)
{
cout << "Unable to open file\n";
return 0;
}
if(myfile.is_open())
{
myfile << "Numbers: \n";
myfile << "90 63 84 52 21 93 77 46\n";
myfile << "90 22 26 34 39 44 75 98\n";
myfile << "28 28 85 57 28 33 66 100\n";
myfile << "16 80 74 62 42 84 42 56\n";
myfile << "85 44 76 97 16 64 80 14\n";
myfile << "41 85 13 88 78 8 18 38\n";
myfile << "53 49 71 79 75 57 93 62\n";
fstream infile;
infile.open("file.txt");
int total, average, max=0, min=0, num;
while(!infile.eof())
{
string line;
getline(infile, line);
int a, b, c, d, e, f, g, h, i;
infile >> a >> b >> c >> d >> e >> f >> g >> h >> i;
total = a+b+c+d+e+f+g+h+i;
average = total/7;
while(infile>>num)
{
max = num;
min = num;
if(max<num)
{
max = num;
}
if(min > num)
{
min = num;
}
}
myfile << " TOTAL AVERAGE MAX MIN\n";
myfile << "90 63 84 52 21 93 77 46 " << total << " " << average << " " << max << " " << min << endl;
myfile << "90 22 26 34 39 44 75 98\n";
myfile << "28 28 85 57 28 33 66 100\n";
myfile << "16 80 74 62 42 84 42 56\n";
myfile << "85 44 76 97 16 64 80 14\n";
myfile << "41 85 13 88 78 8 18 38\n";
myfile << "53 49 71 79 75 57 93 62\n";
}
infile.close();
}
myfile.close();
return 0;
}
【问题讨论】:
-
您正在使用
getline忽略该行... -
抱歉,您能详细说明一下吗?在这里对 c++ 超级新手。我试过查找这个问题,我看过的大多数代码都使用 getline 。它应该看起来如何?