Sunday, May 10, 2009

Reading a file by fstream in c++?

when i open a file and readit then print contints on screen by:


while(! i.eof())


{


i.get(ch);


cout%26lt;%26lt;ch;





}


why it repeats the last charecter twice? how can i avoid that?

Reading a file by fstream in c++?
you should use





while (i.good())


{


i.get(ch);


cout %26lt;%26lt; ch;


}





you get twice the last character because the first time it returns the actual last character of the stream, then in the next iteration it triggers the EOF condition while retaining the previous value.





summing up: i.eof() is only meaningful AFTER a read operation has triggered the EOF bit.





bye


No comments:

Post a Comment