參考資料:《C++ Primer習(xí)題集(第5版)》
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>//處理異常;
using namespace std;
istream &f(istream &in) {//不能拷貝IO對象, 不能將形參或返回類型設(shè)置為流類型;//進(jìn)行IO操作的函數(shù)通常以引用方式傳遞和返回值;
string v;
while (in >> v, !in.eof()) {//直到遇到文件結(jié)束符才停止讀取;
if (in.bad()) {//不可恢復(fù)的錯誤, IO流崩潰;
throw runtime_error("IO流錯誤");//拋出異常;
}
if (in.fail()) {//可以恢復(fù)的錯誤;//比如輸入類型不匹配;
cerr << "數(shù)據(jù)錯誤, 請重試: " << endl;
in.clear();//將in中所有條件狀態(tài)位復(fù)位, 將流的狀態(tài)設(shè)置為有效, 返回void;//恢復(fù)正常;
in.ignore(100, '\n');//讀取并忽略最多100個字符, 包括'\n';
continue;
}
cout << v << endl;
}
in.clear();
return in;//返回引用;
}//讀寫一個IO對象會改變其狀態(tài), 因此傳遞和返回的引用不能是const的;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
ostringstream msg;//字符串輸出流;//向string寫入數(shù)據(jù);
msg << "C++ Primer 第五版" << endl;
istringstream in(msg.str());//strm.str() : 返回strm所保存的string拷貝;
f(in);
return 0;
}
//執(zhí)行結(jié)果;
/*
C++
Primer
第五版
*/
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者