36、stringstream
std::stringstream
是 C++ 标准库中的一个类,位于 <sstream>
头文件中。
它提供了一个在内存中操作字符串的流对象,类似于 std::iostream
,
但它的输入和输出目标是字符串而不是文件或控制台。
以下是 std::stringstream
的一些常见用法:
-
创建字符串流对象:
std::stringstream ss;
-
向字符串流中插入数据:
ss << "Hello, " << "world!" << 123;
-
从字符串流中提取数据:
std::string str; ss >> str; // 提取到第一个空格或换行符
-
将字符串流转换为字符串:
std::string result = ss.str();
-
从字符串初始化字符串流:
std::string input = "123 456"; std::stringstream ss(input); int a, b; ss >> a >> b; // a = 123, b = 456
-
清空字符串流:
ss.str(""); // 清空内容 ss.clear(); // 重置状态标志
示例代码
下面是一个简单的示例,展示了如何使用 std::stringstream
:
#include <iostream>
#include <sstream>
#include <string>int main() {// 创建字符串流对象std::stringstream ss;// 向字符串流中插入数据ss << "Hello, " << "world!" << 123;std::string result = ss.str();std::cout << "Result: " << result << std::endl;std::string input = "123 456";std::stringstream ss2(input);int a, b;ss2 >> a >> b;std::cout << "a: " << a << ", b: " << b << std::endl;int f;std::cin>>f;return 0;
}/*
Result: Hello, world!123
a: 123, b: 456
*/
这个示例展示了如何创建字符串流、插入数据、提取数据以及将字符串流转换为字符串。