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

在C++中,stringstream 是处理字符串与基本数据类型之间转换、拼接字符串的实用工具。它定义在
stringstream 类似于 cin 和 cout,但以字符串为输入输出对象。你可以向其中写入数据,也可以从中读取数据。
常用类型有三种:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
// 写入数据
ss << "年龄:" << 25 << ",身高:" << 178.5;
// 读取整个字符串
string result;
result = ss.str(); // 获取当前内容
cout << result << endl; // 输出:年龄:25,身高:178.5
return 0;
}
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
重复使用同一个 stringstream 时,必须清空其状态和内容,否则后续操作可能出错。
正确做法:
ss.str(""); // 清空字符串内容
ss.clear(); // 清除错误状态(如 eof、failbit)
stringstream ss;
for (int i = 1; i <= 3; ++i) {
ss.str("");
ss.clear();
ss << "编号:" << i;
cout << ss.str() << endl;
}
结合 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 等不安全函数的使用,在实际编程中值得优先考虑。以上就是C++ stringstream怎么用_C++字符串流进行类型转换与拼接的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号