c++ - Why is iostream::eof inside a loop condition considered wrong? -
i found comment in this answer saying using iostream::eof
in loop condition "almost wrong". use while(cin>>n)
- guess implicitly checks eof, why checking eof explicitly using iostream::eof
wrong?
how different using scanf("...",...)!=eof
in c (which use no problems)?
because iostream::eof
return true
after reading end of stream. not indicate, next read end of stream.
consider (and assume next read @ end of stream):
while(!instream.eof()){ int data; // yay, not end of stream yet, read ... instream >> data; // oh crap, read end , *only* eof bit set (as fail bit) // stuff (now uninitialized) data }
against this:
int data; while(instream >> data){ // when land here, can sure read successful. // if wasn't, returned stream operator>> converted false // , loop wouldn't entered // stuff correctly initialized data (hopefully) }
and on second question: because
if(scanf("...",...)!=eof)
is same as
if(!(instream >> data).eof())
and not same as
if(!instream.eof()) infile >> data
Comments
Post a Comment