extra line being read from file

I'm making a banking program for my algorithms and data structures class. Everything is working fine except for this bit where even though I used while accountListIn.good() the program still retrieves an extra blank line from the file. For example, if lab4.csv is the the only account file listed, the output is:

[0] Open New Account
[1] lab4
[2]

Can anyone explain why this might be happening?

FYI: The list of accounts being read is just a .txt file with an account name on each line. The account files themselves are .csv

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
while (accountListIn.good()){
             getline (accountListIn, account[numberOfAccounts+1]);
             numberOfAccounts++;
       }
       
       accountListIn.close();
       
       do{
           invalidSelection = false;
           
           cout << "\nPlease choose the account you would like to work with:"
                << endl << endl << "[0] Open New Account" << endl;
           
           for (int i = 0; i < numberOfAccounts; i++){
               cout << "[" << i+1 << "] " << account[i+1] << endl;
           }
...
Well, it doesn't actually read an extra blank line. It's just that the counter numberOfAccounts is always incremented regardless of whether or not the getline() was successful.

You could fix it like this:
1
2
3
4
5
6
while (accountListIn.good())
{
    getline (accountListIn, account[numberOfAccounts+1]);
    if (accountListIn)
        numberOfAccounts++;
}


But a more usual approach is to test whether the input operation was successful as part of the while condition:
1
2
3
4
while (getline (accountListIn, account[numberOfAccounts+1]) )
{
    numberOfAccounts++;
}

I think the weird "}" might be causing a little confusion (when I pasted the code it got shifted) but that is for the while loop at the top. So the getline itself should only be executing if "accountListIn.good()" is true and thus the same goes for incrementing numberOfAccounts.
Yes, but accountListIn.good() only becomes false AFTER it has tried to read and there is nothing there, setting the eofbit. This means that the input is still good, but you don't read anything, and then increment the numberOfAccounts anyway.
So the getline itself should only be executing if "accountListIn.good()" is true and thus the same goes for incrementing numberOfAccounts.

Correct.

The previous getline was successful, and afterwards, accountListIn.good() will be true.

Then the body of the loop is entered.The getline() is executed, this time it fails (because there is no more data in the file). But even though the operation has failed, the count is still incremented.
Alright I see what you're saying Chervil taht makes sense now. Thanks for the help I added the if statement and it doesn't print the blank line now. NT3 thank you as well
By the way, where did you come by this whole "while (accountListIn.good())" syntax?
Topic archived. No new replies allowed.