Hello, I need some help implementing stringstream in my program. The main problem with my program is that it repeats the last number. Chervil was kind enough to give me the correct way to deal with this, by utilizing a break within the loop, but my teacher doesn't want us using breaks in this program.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
usingnamespace std;
constint 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 < 7; 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;
}
The (simplified) logic would be something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
string line;
while (getline(fileIn, line))
{
istringstream ss(line);
int num;
while (ss >> num)
{
cout << num << " ";
}
cout << endl;
}
I used the cout here simply to illustrate that the data was being read correctly. How you process it is up to you.
By the way, I wouldn't consider my previous response to be "the correct way", rather it was one possible way of fixing the existing code with the minimum amount of changes.