c++ io条件状态 的一个例子
//以下是一個例子,假設從標準輸入的是: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;
 }?
 ?
總結
以上是生活随笔為你收集整理的c++ io条件状态 的一个例子的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: c++问题,EOF eofbit eof
- 下一篇: c++ 中的 cin.get()函数
