我的作业是生成一个包含随机行数的 txt 文件,每行都有随机数量的整数,范围在最小值和最大值之间。很多 rand() 的乐趣。
无论如何,这是最容易的部分。问题的第二部分是读取第一个文件并创建第二个文件,其中包含一些统计信息,例如:文件中所有整数的总和,它们的平均值,最小值和最大值,以及我的主要问题:总和每行中的所有整数。
我写了以下代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
string newLine;
stringstream ss;
int newInput = 0, oldInput = 0;
int lineSum = 0;
int lineCounter = 0;
int allSum = 0;
int intCounter = 0;
double averageOfAll = 0;
int minInt = 0;
int maxInt = 0;
.... // 生成第一个文件。这里没有问题。
ifstream readFile;
readFile.open("inputFile.txt");
ofstream statFile;
statFile.open("stat.txt");
if(readFile.is_open()) {
while (getline(readFile, newLine)) { //my problem should be somewhere
//around here...
ss.str("");
ss << newLine;
while(!ss.eof()) {
oldInput = newInput;
ss >> newInput;
cout << newInput << endl;
lineSum += newInput;
allSum += newInput;
intCounter++;
minInt = min(oldInput, newInput);
maxInt = max(oldInput, newInput);
}
lineCounter++;
statFile << "The sum of all integers in line " << lineCounter
<< " is: " << lineSum << endl;
lineSum = 0;
}
readFile.close();
averageOfAll = static_cast<double>(allSum)/intCounter;
statFile << endl << endl << "The sum of all integers in the whole file: "
<< allSum;
statFile << endl << "The average of value of the whole stream of numbers: "
<< averageOfAll;
statFile << endl << "The minimum integer in the input file: "
<< minInt;
statFile << endl << "The maximum integer in the input file: "
<< maxInt;
statFile << endl << endl << "End of file\n";
} else
cout << endl << "ERROR: Unable to open file.\n";
statFile.close();
return 0;
}
运行程序时,似乎我的循环确实遍历了文件中的所有行。但是,它们只收集第一行的整数,其余的仍然为 0。
我会发布我的输出截图,但我没有足够的代表:(有人可以帮忙吗?
有效!
输入文件.txt ^
statFile.txt(我的输出)^
就像 P0W 和 James Kanze 建议的那样,这是一个标志问题,也是对我的流字符串的滥用。我更正了我的代码如下:
.
.
.
while (getline(readFile, newLine)) {
stringstream ss(newLine);
while(ss >> newInput) {
lineSum += newInput;
allSum += newInput;
intCounter++;
minInt = min(minInt, newInput);
maxInt = max(maxInt, newInput);
}
.
.
.
谢谢你们!