clear

C++ Reference

clear
Syntax:
  #include <fstream>
  void clear( iostate flags = ios::goodbit );

The function clear() does two things:

  • it clears all io stream state flags associated with the current stream,
  • and sets the flags denoted by flags

The flags argument defaults to ios::goodbit, which means that by default, all flags will be cleared and ios::goodbit will be set.

Example code:

For example, the following code uses the clear() function to reset the flags of an output file stream, after an attempt is made to read from that output stream:

 fstream outputFile( "output.txt", fstream::out );            

 // try to read from the output stream; this shouldn't work
 int val;
 outputFile >> val;
 if( outputFile.fail() ) {
   cout << "Error reading from the output stream" << endl;
   // reset the flags associated with the stream
   outputFile.clear();
 }              
                

 for( int i = 0; i < 10; i++ ) {
   outputFile << i << " ";
 }
 outputFile << endl;              
Related topics: