First of all, you should not check like that. eof() does not return true until after it is read. But you can do better (and easier)!
check the state of a stream with an implicit conversion to void* , which can be used in a bool context . Since most read operations in streams return a reference to the stream, you can write very consensus code as follows:
std::string line; while(std::getline(currentfile, line)) { // process line }
Basically, what he does is say, "while I was able to successfully extract the string from the currentfile , do the following", which you really wanted to say anyway; -);
As 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 . I would rewrite your code 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 }
Evan teran
source share