stringstream 是 C++ 中的一個類,它位于 <sstream> 頭文件中。這個類允許你在內存中讀寫字符串,就像操作文件一樣。它常常用于處理字符串格式的數據,比如將一個整數和一個字符串組合成一個復雜的字符串。
下面是一些基本的使用示例:
1. 包含頭文件
#include <iostream>
#include <sstream>
#include <string>
2. 創建一個 stringstream 對象
std::stringstream ss;
3. 使用 << 運算符向 stringstream 寫入數據
ss << "Hello, " << "World!" << std::ends; // 注意 std::ends 用于添加一個空行
4. 使用 >> 運算符從 stringstream 讀取數據
std::string str;
int num;
ss >> str >> num; // 從 stringstream 中讀取一個字符串和一個整數
std::cout << "String: " << str << ", Number: " << num << std::endl;
在這個例子中,str 變量將存儲 “Hello, World!”,而 num 變量將存儲 0(因為這里沒有明確指定要讀取的整數值,所以默認讀取的是 0)。
5. 其他一些有用的成員函數
str():返回 stringstream 中存儲的字符串。clear():清除 stringstream 中的所有錯誤標志。fail():檢查 stringstream 是否遇到了錯誤。eof():檢查是否已經讀取到了 stringstream 的末尾。例如:
std::stringstream ss;
ss << "123 456 789";
int a, b, c;
ss >> a >> b >> c;
if (!ss.fail()) {
std::cout << "a: "<< a << ", b: "<< b << ", c: "<< c << std::endl;
} else {
std::cout << "Error occurred while reading." << std::endl;
}
在這個例子中,ss.fail() 將返回 false,因為讀取操作成功完成了。如果在讀取過程中遇到錯誤,fail() 將返回 true。