c++ - Behavior of fstream as a bool and fstream.good() function -


i used fstream homework assignment , wondering how 2 things worked.

#include <iostream> #include <fstream>  using namespace std;  int main(int argc, char** argv) {      ifstream myfile;     myfile.open("fileone.txt");     int myint = 0;      while (myfile.good()) { // difference between myfile , myfile.good()?         if (!myfile.eof()){             myfile >> myint;             cout << myint << endl;         }     }      return 0; } 

this snippet of actual code working on. in post, said if used while(myfile) , automatically convert bool. difference between using , using member function .good() of ifstream class? know .good() breaks out of while loop when reach end of text file how using stream name behave?

iostream classes have 4 functions assessing stream state: good(), bad(), fail(), , eof(). excluding good(), each function checks single bit in underlying stream state , returns whether or not bit on (are there errors?). good() in particular checks if all bits off (is stream valid?). these for:

  • good(): stream has not encountered error.
  • bad(): stream has encountered error effects integrity of stream (i.e memory allocation failure, no buffer, etc.)
  • fail(): typically recoverable error (formatting/parsing failure).
  • eof(): end-of-file (eof) character has been reached.

when performing i/o, integral check errors in stream while processing input. novices typically don't know only function meant used check valid input fail(). other functions useful in other cases not conditioning input.

futhermore, novices fail realize input must performed before checking errors. doing otherwise allows unchecked extraction, allowing body of loop access value not produced valid extraction.

streams have boolean operator returns !fail(), allows check stream in elegant way after performing input, this:

while (myfile >> myint) {     // ... } 

this best way perform input. extraction should present within conditional context body of whatever being used in executed if extraction succeeded.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -