//以下是一個例子,假設從標準輸入的是: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;} //這裡cin會把所有的字元輸入到i_number裡面(因為輸入字元,所以i_number得到0)。包括空格(這裡把輸入的第一個空格以前的所有字元給它,然後其餘的所有字元都存在cin中危險哦,所以導致cin流發生錯誤)
cout<<"inumber_is:" <<i_number << endl;
cout << "cin 's rdstate:" << cin.rdstate() << endl; //流髮色錯誤,那麼failbit被置位,所以這裡值是4
ios::iostate old_state = cin.rdstate(); //記住cin此時的錯誤,把他放在ios::iostate(這是個型別,可以存放所有的標誌位型別)型別的old_state內
ios::iostate a = cin.goodbit; //定義a代表常數 goodbit的值 0
ios::iostate b = cin.badbit; //定義b代表常數 badbit的值 1
ios::iostate c = cin.eofbit; //定義c代表常數 eofbit的值 2
istream::iostate d = cin.failbit; //定義d代表常數 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"); //定義一個ifstream(讀取用)物件,準備讀取檔案2.txt內容
ofstream f2("2.txt"); //定義一個ofstream(寫入用) 物件,準備寫入到檔案2.txt
string str3; //定一個一個string物件
fff >> str3; //從檔案流物件fff讀入到str3
cout << fff.rdstate() << endl; //at last ,his ' s state is 6;
//f2.clear(cin.rdstate());
cout << "cin'rdstate " <<cin.rdstate() << endl; //輸出此時的cin流的狀態資訊
cout << "fff.rdstate*() is:"<<fff.rdstate() << endl; //輸出fff流的狀態資訊
fff.setstate(cin.rdstate()); //把流cin的狀態資訊新增到fff中(fff原有狀態資訊不變)
fff.clear(cin.rdstate()); //用cin狀態資訊替換fff狀態資訊
cout << fff.rdstate() << endl;
char ch;
cout <<"cin.rdstate() is:" <<cin.rdstate() << endl;
cin.clear(); //復位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') //輸出記憶體中cin中的所有字元(cin有一部分內容殘留)
cout << "has char: " << ch << endl;
cin >> s5;
cout << "s5 comes again:" << s5<< endl;
return 0;
}