Clarens
Clarens

Reputation: 21

Last empty line and ifstream::operator>> (C++)

I have a question about the ifstream::operator>> behavior in the following code:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main () {
    ifstream inFile("test.txt");
    string buffer;
    while (!inFile.eof()) {
        inFile >> buffer;
        cout << buffer << endl;
    }
    return 0;
}

This code works perfectly well if the last line of test.txt is not empty, for instance :

One two
Three four
Five six

However if test.txt is written like that :

One two
Three four
Five six
(empty line)

The cout will display two "six" strings. Is it a problem related to the \r\n of Windows or something like that ? I use Microsoft VC++ 2010.

Thanks in advance.

Upvotes: 2

Views: 1499

Answers (2)

SHR
SHR

Reputation: 8313

Before the read it wasn't EOF yet. But last read action has failed due to EOF reach.

You can use fail to check if your last read failed:

int main () {
    ifstream inFile("test.txt");
    string buffer;
    while (!inFile.eof()) {
        inFile >> buffer;
       /**EDIT**/
       if(!inFile.fail()){
            cout << buffer << endl;
        }else{
            cout << endl;
        }
    }
    return 0;
}

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

Using stream.eof() for loop control us normally wrong: you always want to check the result after reading:

while (inFile >> buffer) {
    ...
}

The formatted read will start with skipping leading whitespace. After that, the string extractor will read non-whitespace characters. If there is no such character, the extraction fails and the stream converts to false.

Upvotes: 3

Related Questions