How does does ifstream eof() work?

Posted by Chan on Stack Overflow See other posts from Stack Overflow or by Chan
Published on 2010-12-26T07:21:52Z Indexed on 2010/12/26 7:53 UTC
Read the original article Hit count: 218

Filed under:

Hello everyone,

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>

using namespace std;

int main() {
    fstream inf( "ex.txt", ios::in );
    while( !inf.eof() ) {
        std::cout << inf.get() << "\n";
    }
    inf.close();
    inf.clear();
    inf.open( "ex.txt", ios::in );
    char c;
    while( inf >> c ) {
        std::cout << c << "\n";
    }
    return 0;
}

I'm really confused about eof() function. Suppose my ex.txt's content is:

abc

It always reads an extra character and show -1. when reading using eof()? But the inf >> c gave the correct output which was 'abc'? Can anyone help me explain this?

Best regards, Chan Nguyen

© Stack Overflow or respective owner

Related posts about c++