C++ 引入 <sstream> 提供三大字符串流類,統一使用 <<(輸出/插入)和 >>(輸入/提取)運算符。
istringstream : istream + stringstreambase(輸入)ostringstream : ostream + stringstreambase(輸出)stringstream : iostream + stringstreambase(雙向)istringstream istr("1 56.7"); // 或 istr.str("1 56.7")
istr >> a >> b;str() 返回當前緩衝區字符串副本。#include
#include
using namespace std;
int main() {
istringstream istr("1 56.7");
cout << istr.str() << endl; // 輸出: 1 56.7
int a; float b;
istr >> a >> b;
cout << a << endl << b << endl; // 1 56.7
return 0;
}
ostringstream ostr;
ostr.put('d');
ostr << "fg";
string s = ostr.str(); // 獲取完整字符串
若構造時已設置初始字符串(ostr.str("abc")),後續插入會覆蓋原內容而非追加,超出部分才增長。
stringstream ss("ccc");
ss.put('d'); ss.put('e'); ss << "fg";
string s = ss.str(); // "cccdefg"
char c; ss >> c; // 讀取 'c'
stringstream 常用於 string 與內置類型雙向轉換:
stringstream sstr;
// int → string
int a = 100; string str;
sstr << a; sstr >> str; // str == "100"
sstr.clear(); // 必須清除狀態標志
// string → char[]
string name = "colinguan"; char cname[200];
sstr << name; sstr >> cname;
關鍵:每次轉換後必須調用 clear() 重置流狀態,否則後續操作失敗。
goodbit:無錯誤eofbit:到達文件尾failbit:非致命錯誤(如類型不匹配),可恢復badbit:致命錯誤,不可恢復rdstate():返回組合狀態位掩碼。good()、eof()、fail()、bad():布爾查詢。cin.clear(ios::goodbit); // 重置為無錯誤狀態
cin.get(); // 消耗緩衝區殘留字符(如換行符)
int a;
while (true) {
cin >> a;
if (!cin) { // 等價 cin.fail()
cout << "輸入錯誤,請重試" << endl;
cin.clear();
cin.get(); // 或 cin.ignore(numeric_limits::max(), '\n');
} else {
cout << a << endl;
break;
}
}
ifstream file("c:\\1.txt");
if (file.fail()) {
cout << "文件打開失敗" << endl;
} else {
char ch;
while (file.get(ch)) cout << ch;
if (file.eof()) cout << "讀取完畢" << endl;
}