Why is my code reading the last Line Twice

Feb 15, 2022 at 8:23pm
This program that i created is working, but it is reading the last line twice. Idk what I did wrong.
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string fileName;
    int maxNum = -100;
    int minNum =  100;
    int numCount = 0;
    int sumNum = 0;




    cout<<"Enter name of the data file: ";
    cin>>fileName;
    ifstream openFile(fileName);
    while(!openFile){
        cout<<"Error opening the file "<<fileName<<" Try Again!!";
        cout<<"Enter name of the data file: ";
        cin>>fileName;
        openFile.open(fileName);
    }

    while (openFile.good())
    {
        int x;
        openFile >> x;
        sumNum += x;
        numCount++;
        if(x>maxNum)maxNum=x;
        if(x<minNum)minNum=x;
    }

    double avg = sumNum/numCount;
    cout<<"Min: = "<<minNum<<endl;
    cout<<"Max: = "<<maxNum<<endl;
    cout<<"Sum: = "<<sumNum<<endl;
    cout<<"Count: = "<<numCount<<endl;
    cout<<"Average: = "<<avg;
    return 0;
}
Feb 15, 2022 at 8:38pm
Don't loop on file.good() or EOF (another mistake that keeps popping up like a weed).
Loop on the successful extraction of data itself.

1
2
3
4
5
6
7
8
    int data;
    while (openFile >> data)
    {
        sumNum += data;
        numCount++;
        if (data > maxNum) maxNum = data;
        if (data < minNum) minNum = data;
    }
Last edited on Feb 15, 2022 at 8:39pm
Feb 15, 2022 at 8:38pm
it is reading the last line twice

Actually, it isn't. It's just that the stream won't go 'bad' until after you have tried and failed to read a value, by which time you are committed to finishing the loop.

Change
1
2
3
4
    while (openFile.good())
    {
        int x;
        openFile >> x;

to just
1
2
3
    int x;
    while (openFile >> x)
    {



Later on, your calculation of the average will be wrong (most of the time) because of integer division.
Last edited on Feb 15, 2022 at 8:41pm
Feb 15, 2022 at 8:39pm
but it is reading the last line twice. Idk what I did wrong.

This is probably because you used good() to control your input loop instead of the actual read. Remember that you are checking the file state before you try to read the file, you need to check the file status after reading the file.

int x;
while(infile >> x)
{
// Whatever.
}
Feb 16, 2022 at 10:16am
If you're been told to use .good() within a loop (bad idea), then you code it like this:

1
2
3
4
5
6
7
8
9
10
while (openFile.good()) {
    int x;

    if (openFile >> x) {
        sumNum += x;
        numCount++;
        if(x>maxNum)maxNum=x;
        if(x<minNum)minNum=x;
    }
}

Topic archived. No new replies allowed.