stringstream是C++中用于字符串与基本类型转换的工具,定义在头文件中,支持读写操作,常用类型有stringstream、istringstream和ostringstream。

在C++中,stringstream 是处理字符串与基本数据类型之间转换、拼接字符串的实用工具。它定义在
1. 基本用法:字符串流的读写操作
stringstream 类似于 cin 和 cout,但以字符串为输入输出对象。你可以向其中写入数据,也可以从中读取数据。
常用类型有三种:
- stringstream:同时支持读写
- istringstream:仅用于从字符串读取(输入)
- ostringstream:仅用于向字符串写入(输出)
#include#include using namespace std; int main() { stringstream ss; // 写入数据 ss << "年龄:" << 25 << ",身高:" << 178.5; // 读取整个字符串 string result; result = ss.str(); // 获取当前内容 cout << result << endl; // 输出:年龄:25,身高:178.5 return 0; }
2. 字符串与数值类型的相互转换
stringstream 最常见的用途之一是实现字符串与 int、double 等类型的转换,比 C 风格的 atoi、atof 更安全灵活。
立即学习“C++免费学习笔记(深入)”;
字符串转数字
string str_num = "12345";
int num;
stringstream ss(str_num); // 初始化时传入字符串
ss >> num;
if (ss.fail()) {
cout << "转换失败" << endl;
} else {
cout << "转换结果:" << num << endl; // 12345
}
数字转字符串
int value = 998; stringstream ss; ss << value; // 将整数写入流 string str_val = ss.str(); // 转为字符串 cout << "字符串值:" << str_val << endl;
你也可以连续写入多个值来拼接:
stringstream ss; ss << 100 << " + " << 200 << " = " << 300; cout << ss.str() << endl; // 100 + 200 = 300
3. 清空 stringstream 的内容
重复使用同一个 stringstream 时,必须清空其状态和内容,否则后续操作可能出错。
正确做法:
ss.str(""); // 清空字符串内容
ss.clear(); // 清除错误状态(如 eof、failbit)
注意:顺序很重要!先 str("") 再 clear()
示例:循环中使用 stringstream
stringstream ss;
for (int i = 1; i <= 3; ++i) {
ss.str("");
ss.clear();
ss << "编号:" << i;
cout << ss.str() << endl;
}
4. 分割字符串并解析字段
结合 getline 函数,stringstream 可用于分割字符串,比如解析 CSV 格式数据。
string line = "张三,20,计算机系"; stringstream ss(line); string name, age, dept; getline(ss, name, ','); // 以逗号分隔 getline(ss, age, ','); getline(ss, dept); cout << "姓名:" << name << endl; cout << "年龄:" << age << endl; cout << "院系:" << dept << endl;
这种用法在读取配置文件或文本数据时非常实用。
基本上就这些。stringstream 提供了一种自然、类型安全的方式来处理字符串拼接与类型转换,避免了 sprintf 等不安全函数的使用,在实际编程中值得优先考虑。










