Need help utilizing stringstream in my program (reading #'s line by line from file)

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.

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

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 < 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;
}
Last edited on
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.
Topic archived. No new replies allowed.