Wrong output?

I am not getting the right output.

input from tests.txt is:

75 85 95 65
89 90 79 87
70 68 77 82
50 92 86 88
87.5 91.5 66.5 78.5

My output is:

Test 1 Test 2 Test 3 Test 4 Average
75.0 85.0 95.0 65.0 85.00
89.0 90.0 79.0 87.0 88.67
70.0 68.0 77.0 82.0 76.33
50.0 92.0 86.0 88.0 88.67
87.5 91.5 66.5 78.5 85.83
87.5 91.5 66.5 78.5 85.83

Why is the last line printing out twice?

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
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

double getAvg(double, double, double, double);

int main ()
{
    double test1;
    double test2;
    double test3;
    double test4;
    double average;

    ifstream inData;
    ofstream outData;

    inData.open("tests.txt");
    outData.open("Lab5a_2_Output.txt");

    outData << fixed << showpoint << setprecision(1);
    outData << "Test 1" << setw(10) << "Test 2" << setw(10) << "Test 3" << setw(10) << "Test 4" << setw(10) << "Average" << endl;

    while( inData )
    {
        inData >> test1 >> test2 >> test3 >> test4;
        average = getAvg(test1, test2, test3, test4);

        outData << test1 << setw(10) << test2 << setw(10) << setw(10) << test3 << setw(10) << test4 << setprecision(2) << setw(10) << average << endl;
        outData << setprecision(1);
    }

    inData.close();
    outData.close();

    return 0;
}
double getAvg(double test1, double test2, double test3, double test4)
{

    double lowest = test1;
    double sum;

    if (test2 < lowest)
        lowest = test2;
    else if(test3 < lowest)
        lowest = test3;
    else if(test4 < lowest)
        lowest = test4;

    sum = test1 + test2 + test3 + test4;
    sum = sum - lowest;
    sum = sum / 3;

    return sum;
}
Use while ( !inData.eof() ). You need to make sure that there are no further lines in your text files. This might work actually, but in all cases you need to parse the file line by line, use getline.

Good luck in your coming lab assignments...
Last edited on
Thanks!
Topic archived. No new replies allowed.