Using the eof(), fail(), bad(), good(), clear() and rdstate() methods C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the eof(), fail(), bad(), good(), clear() and rdstate() methods in C++ programming

To show: How to use the eof(), fail(), bad(), good(), clear() and rdstate() methods in C++ programming

 

// using eof(), fail(), bad(), good(), clear() and rdstate() functions

#include <iostream>

using namespace std;

 

void main(void)

{

int p;

 

cout<<"Before a bad input operation: \n"

<<"-----------------------------\n"

<<" cin.rdstate(): "<<cin.rdstate()

<<"\n cin.eof(): "<<cin.eof()

<<"\n cin.fail(): "<<cin.fail()

<<"\n cin.bad(): "<<cin.bad()

<<"\n cin.good(): "<<cin.good()

<<"\n\nEnter a character (should be integer): "<<endl>>p;

cout<<"After a bad input operation: \n"

<<"----------------------------\n"

<<" cin.rdstate(): "<<cin.rdstate()

<<"\n cin.eof(): "<<cin.eof()

<<"\n cin.fail(): "<<cin.fail()

<<"\n cin.bad(): "<<cin.bad()

<<"\n cin.good(): "<<cin.good()<<"\n\n";

cin.clear();

cout<<"After cin.clear()\n"

<<"-----------------\n"

<<"cin.fail(): "<<cin.fail()<<endl;

 

return;

}

 

Output example:

 

Before a bad input operation:

-----------------------------

cin.rdstate(): 0

cin.eof(): 0

cin.fail(): 0

cin.bad(): 0

cin.good(): 1

Enter a character (should be integer):

F

After a bad input operation:

----------------------------

cin.rdstate(): 2

cin.eof(): 0

cin.fail(): 1

cin.bad(): 0

cin.good(): 0

After cin.clear()

-----------------

cin.fail(): 0

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index