ifstream not reading EOF character

First thing is first, you shouldn’t check like that. eof() doesn’t return true until after a failed read. But you can do better (and easier)!

check the stream state with the implicit conversion to void* which can be used in a bool context. Since most of the read operations on streams return a reference to the stream, you can write some very consice code like this:

std::string line;
while(std::getline(currentfile, line)) {
    // process line
}

Basically what it is doing is saying “while I could successfully extract a line from currentfile, do the following”, which is what you really meant to say anyway ;-);

Like I said, this applies to most stream operations, so you can do things like this:

int x;
std::string y;
if(std::cin >> x >> y) {
    // successfully read an integer and a string from cin!
}

EDIT: The way I would rewrite your code is like this:

string line;
unsigned long pos = 0;
int linenumber = 0;

ifstream curfile(input.c_str());

std::cout << "About to try to read the file" << std::endl;
while (std::getline(curfile, line)) {

    std::cout << "Getting line " << linenumber << std::endl;
    linenumber++;

    // do the rest of the work with line
}

Leave a Comment