clear

Syntax:

    void stream::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. 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.

Example code:

   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: eof, fail, good, rdstate