getline reads one line too much

Hi,
so I want to read a text file line by line, so that each row should be stored in a string. The text file looks like this:

name1;phone_number1;address1
name2;phone_number2;address2
...


So I wrote the following function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void filereader (char * location) {
    string aString;
    ifstream inputstream;
    inputstream.open(location, ios:: in);
    if(inputstream){
        while(!inputstream.eof()){
            getline(inputstream, aString);
            cout <<"getline: \""<< aString << "\"" <<endl; //  testing
        }
    }
    else{
        cout <<"file not found!" <<endl;
    }
    inputstream.close ();
    inputstream.clear ();
}

Unfortunately, the program is reading one line too much and the output is looking like this:

"name1;phone_number1;address1"
"name2;phone_number2;address2"
""

At first I thought it was a "\n" or "\0". That's why I added an if statement ..
1
2
if (aString != "\n")
cout << "getline: \"" << aString << "\"" << endl;

.. it doesn't wordk.

How can I avoid this superfluous string?
I'm using Netbeans + Ubuntu

Thanks in advance
Last edited on
You need to check for eof after reading aString, the last input operation will always fail
Wow that's worked! Thank you very much.
Topic archived. No new replies allowed.