Saturday, December 29, 2018

c++ - Reading a text document character by character




I am reading a text file character by character using ifstream infile.get() in an infinite while loop.



This sits inside an infinite while loop, and should break out of it once the end of file condition is reached. (EOF). The while loop itself sits within a function of type void.



Here is the pseudo-code:



void function (...) {
while(true) {
...

if ( (ch = infile.get()) == EOF) {return;}
...
}
}


When I "cout" characters on the screen, it goes through all the character and then keeps running outputting what appears as blank space, i.e. it never breaks. I have no idea why. Any ideas?


Answer



In C++, you don't compare the return value with EOF. Instead, you can use a stream function such as good() to check if more data can be read. Something like this:




while (infile.good()) {
ch = infile.get();
// ...
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...