An example of c++ io conditional state

//The following is an example, assuming that the standard input is: aab asdf asdf asdf asdf

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{   int i_number; cout << "input i_number:"<<endl;   while(cin >> i_number )    {cout << i_number << endl;} //Here cin will enter all characters into i_number (because of the input characters, i_number gets 0). Including spaces (here, give it all the characters before the first space entered, and then all the remaining characters are dangerous in cin, so an error occurs in the cin stream) cout<<"inumber_is:" <<i_number << endl ; cout << "cin's rdstate:" << cin.rdstate() << endl; //The flow color is wrong, then the failbit is set, so the value here is 4 ios::iostate old_state = cin.rdstate( ); //Remember the error of cin at this time, put him in ios::iostate (this is a type,








ios::iostate b = cin.badbit; //define b to represent the value of constant badbit 1
ios::iostate c = cin.eofbit; //define c to represent the value of constant eofbit 2
istream::iostate d = cin.failbit; //Define d to represent the value of the constant failbit 4
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "after been given character ,cin's state is: "<< cin.rdstate() << endl;
ifstream fff("2.txt"); //Define an ifstream (for reading) object, ready to read the content of file 2.txt
ofstream f2("2.txt"); //Define an ofstream (for writing) object, ready to be written to the file
2.txt string str3; //Define a string object
fff >> str3;//Read from the file stream object fff to str3
cout << fff.rdstate() << endl; //at last ,his' s state is 6;
//f2.clear(cin.rdstate());
cout << "cin'rdstate" <<cin.rdstate() << endl; //output the state information of the cin stream at this time
cout << "fff.rdstate *() is:"<<fff.rdstate() << endl; //Output the status information of the fff stream
fff.setstate(cin.rdstate()); //Add the status information of the stream cin to fff (fff The original state information remains unchanged)
fff.clear(cin.rdstate()); //Replace fff state information with cin state information
cout << fff.rdstate() << endl;                 
char ch;
cout <<"cin.rdstate () is:" <<cin.rdstate() << endl;
cin.clear(); //Reset cin
string s5;                           
cin >> s5;
cout << "s5:"<< endl; 
cout <<"after clear:"<< cin.rdstate() << endl;
cout << "before while loop: there" << endl;
while((ch = cin.get()) !='\n') //Output all characters in cin in memory (part of cin remains)
  cout << "has char: "<< ch << endl;              
cin >> s5;
cout << "s5 comes again:" << s5<< endl;
  return 0;

 

Guess you like

Origin blog.csdn.net/digitalkee/article/details/108894265