stringstream 是 C++ 标准库中的一个非常有用的类,它允许你像操作输入/输出流一样操作字符串。它是 <sstream> 头文件中定义的类,结合了字符串和流的特性。
std::stringstream //用于读写字符串
std::istringstream //只用于从字符串读取
std::ostringstream //只用于向字符串写入
基本用法
#include <iostream>
#include <sstream> //包含头文件
#include <string>
using namespace std;
int main() {
stringstream ss; //创建对象
ss << "Hello" << " " << "World!" << " " << "2025"; //往ss写入数据
string content = ss.str(); //获取字符串内容
cout << "content: " << content << endl;
string p1, p2;
int year;
ss >> p1 >> p2 >> year; //从ss中读取数据
cout << "p1: " << p1 << endl << "p2: " << p2
<< endl << "year: " << year << endl;
return 0;
}
实际应用案例
(1)字符串拼接
std::stringstream ss;
ss << "The answer is: " << 42;
std::string result = ss.str(); // "The answer is: 42"
也可以用 +、+=、string类中的append方法,等等。
虽然stringstream 通常比直接字符串拼接效率低,但在需要复杂格式化时非常有用。
(2)字符串分割
std::string data = "John,Doe,30";
std::stringstream ss(data);
std::string token;
while (std::getline(ss, token, ',')) {
std::cout << token << std::endl;
}
// 输出:
// John
// Doe
// 30
(3)类型转换
std::string numStr = "123.45";
std::stringstream ss(numStr);
double num;
ss >> num; // 将字符串转换为double
但是一般使用C++11引入的std::to_string函数(包含string头文件)更加方便:
int i = 42;
std::string s = std::to_string(i); // "42"
double d = 3.14;
std::string s2 = std::to_string(d); // "3.140000"
float f = 2.5f;
std::string s3 = std::to_string(f); // "2.500000"
此外,还有反向转换(字符串转数值)
std::stoi() //转 int
std::stol() //转 long
std::stoll() //转 long long
std::stoul() //转 unsigned long
std::stoull() //转 unsigned long long
std::stof() //转 float
std::stod() //转 double
std::stold() //转 long double
stringstream重要成员函数介绍
(1)str() :获取或设置字符串内容
std::string content = ss.str(); // 获取
ss.str("New content"); // 设置
(2)clear() :清除错误状态标志
ss.clear(); // 清除可能出现的错误状态
重复使用同一个 stringstream 对象时,最好先调用 clear() 清除状态,然后调用 str("") 清空内容。
2万+

被折叠的 条评论
为什么被折叠?



