## Tuesday, November 22, 2011

### How to test Stream Errors in C++?

The objects cin and cout works well in normal conditions for input and output respectively. However, there can be several abnormal situation in I/O process such as entering string instead of digit, pressing enter key without entering value or some hardware failure. When errors occurred during input or output operations, the errors are reported by stream state. Every stream (istream or ostream) has a state associated with it. Error conditions are detected and handled by testing the state of the steam. Following are the member functions of ios class that are used to test the state of the stream.
bool ios::good() : This function returns true when everything is okay, that is , when there is no error conditions.
bool ios::eof(): This function returns true if the input operation reached end of input sequence.
bool ios::bad(): This function returns true if the stream is corrupted and no read/write operation can be performed. For example in an irrecoverable read error from a file.
bool ios::fail(): This functions returns true if the input operation failed to read the expected characters, or that an output operation failed to generate the desired characters. When in fail condition the stream may not be corrupted.
void ios::clear(ios::iostate f = ios::goodbit): This function clears all the flag if no argument is supplied. It can also be used to clear a particular state flag if supplied as argument.
ios::iostate ios::rdstate(): This function returns the state of a stream object of type iosteate.
void ios::setstate(ios::iostate f): This function adds the flag in argument to the iostate flags.
ios::goodbit : This state flag indicates that there is no error with streams. In this case the status variables has value 0.
ios::eofbit: This state flag indicates that the input operation reached end of input sequence.
ios::badbit: This state flag indicates that the stream is corrupted and no read/write operation can be performed.
ios::failbit: indicates that input/output operation failed. The fail condition may not be because of corrupted stream.
The sample source code that illustrates the concept of testing stream error is presented below
#include<iostream>

using std::cout;
using std::endl;
using std::cin;
using std::ios;

int main()
{
int integerValue;

cout<<"Before a Bad input operation: "
<<"\ncin.rdstate(): "<<cin.rdstate()
<<"\n cin.eof():"<<cin.eof()
<<"\ncin.fail(): "<<cin.fail()
<<"\ncin.good(): "<<cin.good()
<<"\n\nExpects an integer, but enter a character: ";

cin>>integerValue;
cout<<endl;

cout<<"After a bad input operation: "
<<"\n cin.rdstate(): "<<cin.rdstate()
<<"\n cin.eof(): "<<cin.eof()
<<"\n cin.fail(): "<<cin.fail()
<<"\n cin.good(): "<<cin.good()
<<endl<<endl;

cin.clear(ios::goodbit);

cout<<"After cin.clear()"
<<"\ncin.fail(): "<<cin.fail()
<<"\ncin.good(): "<<cin.good()<<endl<<endl;

return 0;

}