I was assigned homework to create a txt file containing a random number of lines, each of which has a random number of integers, starting from the minimum value and maximum value. A large number of rands ().
In any case, it was the easy part. The second part of the problem is to read the first file and create a second file containing some statistics, such as: the sum of all integers in the file, their average value, the minimum and maximum values ββand my main problem: the sum of all integers in each line.
I wrote the following code:
#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;
.... // generate the first file. There is no problem.
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; }
When the program starts, it seems that my loops iterate over all the lines in the file. However, they only collect integers from the first line, and the rest remain 0.
I would post screenshots of my speeches, but I don't have enough reputation :( can anyone help?
It worked!
inputFile.txt ^ 

statFile.txt (my conclusion) ^
And, as P0W and James Kanze suggested, this was a flag issue and misuse of my streamstring. I adjusted my code as follows:
. . . while (getline(readFile, newLine)) { stringstream ss(newLine); while(ss >> newInput) { lineSum += newInput; allSum += newInput; intCounter++; minInt = min(minInt, newInput); maxInt = max(maxInt, newInput); } . . .
Thanks everyone!