c++ - Testing stream.good() or !stream.eof() reads last line twice -


possible duplicate:
why iostream::eof inside loop condition considered wrong?

i have following piece of code:

ifstream f("x.txt"); string line; while (f.good()) {   getline(f, line);   // use line here. } 

but reads last line twice. why happen , how fix it?

something similar happens with:

ifstream f("x.txt"); string line; while (!f.eof()) {   getline(f, line);   // use line here. } 

you very, want check bad, eof, , good. in particular eof (as !stream.eof() common mistake), stream being @ eof not mean last input operation failed; conversely, not being @ eof not mean last input successful.

all of stream state functions – fail, bad, eof, , – tell current state of stream rather predicting success of future operation. check stream (which equivalent inverted fail check) after desired operation:

if (getline(stream, line)) {   use(line); } else {   handle_error(); }  if (stream >> foo >> bar) {   use(foo, bar); } else {   handle_error(); }  if (!(stream >> foo)) {  // operator! overloaded streams   throw someexception(); } use(foo); 

to read , process lines:

for (std::string line; getline(stream, line);) {   process(line); } 

pointedly, good() misnamed , not equivalent testing stream (which above examples do).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -