概述
<sstream> 定義了三個類:
istringstream |
流的輸入 |
ostringtream |
流的輸出 |
stringstream |
流的輸入輸出 |
<sstream>主要用來進行數據類型轉換。
<sstream>使用string對象來代替字符數組(snprintf方式),能避免緩沖區溢出的危險;而且,因為傳入參數和目標對象的類型會被自動推導出來,所以不存在錯誤的格式化符的問題。
簡單說,相比C語言自帶的庫的數據類型轉換而言,<sstream>更加安全、自動和直接。
用法
-
數據類型轉換
demo
#include <sstream> #include <iostream> using namespace std;
int main() { stringstream sstream; string strResult; int nValue = 1000;
// 將int類型的值放入輸入流中 sstream << nValue;
// 從sstream中抽取前面插入的int類型的值,賦給string類型 sstream >> strResult;
return 0; } |
- 清空sstream
進行多次類型轉換前 |
必須清空,否則可能得不到正確結果。
|
|
字符串拼接 |
可使用
|
-
字符串拼接
demo
#include <string> #include <sstream> #include <iostream> using namespace std;
int main() { stringstream sstream;
// 將多個字符串放入 sstream 中 sstream << "first" << " " << "string,"; sstream << " second string";
cout << "strResult is: " << sstream.str() << endl;
// 清空 sstream sstream.str(""); sstream << "third string";
cout << "After clear, strResult is: " << sstream.str() << endl; return 0; } |
