std::stringstream 是 C++ 标准库中定义的类,位于 <sstream> 头文件中。它是一个可以在字符串和流之间进行转换的工具,支持从字符串中读取数据或向字符串写入数据。
stringstream 的构造函数和参数:
stringstream 的构造函数有多个重载版本:
- 默认构造:
- stringstream(); //创建一个空的字符串流对象
- 用字符串初始化:
- stringstream(const string& str); //通过传递一个字符串来初始化流对象。并将该字符串内容放入流中。
- 带格式标志的构造:
- stringstream(ios_base::openmode mode); //使用指定的模式构造,比如输入模式(ios::in) 输出模式(ios::out);
- 完整构造:
- stringstream(const string& str, ios_base::openmode mode); //用指定的字符串和模式初始化流
主要成员函数:
1. 输入操作
- 从 stringstream中读取数据:ss >> variable;
- ss("123 45.6 hello");
- int a;double b;string c;
- ss >> a >> b >> c;
- // a = 123, b = 45.6, c = "hello"
2. 输出操作
- 向stringstream中写入数据:ss << variable;
- ss;
- ss << "Hello " << 2024;
- cout << ss.str();
- // 输出: Hello 2024
3. 获取或设置内容
- 获取流中的字符串内容:
- string str = ss.str(); //示例:
- stringstream ss;
- ss << 42 << " apples";
- cout << ss.str();
- // 输出: 42 apples
- string str = ss.str(); //示例:
- 设置新的字符串到流中(清空并重新加载):
- ss.str("new content");
4. 清空流
- 清除流的内容:
- ss.str(""); // 清空内容
- ss.clear(); // 重置状态标志(比如 eof, fail)
用法示例:
1. 解析字符串
用于将字符串分割成多个部分并处理:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string data = "123 456 789";
stringstream ss(data);
int num;
while (ss >> num) {
cout << num << endl;
}
return 0;
}
输出:
123
456
789
2. 拼接字符串
可以使用 stringstream 将不同类型的数据拼接成一个字符串:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss << "The result is: " << 42 << " and the value is: " << 3.14;
cout << ss.str() << endl; // 输出: The result is: 42 and the value is: 3.14
return 0;
}
3. 分割字符串
通过指定分隔符,可以手动分割字符串:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string data = "apple,banana,grape";
stringstream ss(data);
string item;
while (getline(ss, item, ',')) {
cout << item << endl;
}
return 0;
}
输出:
apple
banana
grape
4. 双向操作
可以先写入,再读取:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss << "123 45.6 test";
int a;
double b;
string c;
ss >> a >> b >> c;
cout << "Integer: " << a << endl; // 输出: Integer: 123
cout << "Double: " << b << endl; // 输出: Double: 45.6
cout << "String: " << c << endl; // 输出: String: test
return 0;
}
总结:
stringstream主要用于:
- 格式化输入和输出: 处理混合类型的数据。
- 字符串解析: 从字符串中提取信息(类似于 scanf 功能)。
- 字符串拼接: 高效地将各种类型的数据拼接成字符串。