36、stringstream

std::stringstream 是 C++ 标准库中的一个类,位于 <sstream> 头文件中。

它提供了一个在内存中操作字符串的流对象,类似于 std::iostream

但它的输入和输出目标是字符串而不是文件或控制台。

以下是 std::stringstream 的一些常见用法:

  1. 创建字符串流对象

    cpp 复制代码
    std::stringstream ss;
  2. 向字符串流中插入数据

    cpp 复制代码
    ss << "Hello, " << "world!" << 123;
  3. 从字符串流中提取数据

    cpp 复制代码
    std::string str;
    ss >> str;  // 提取到第一个空格或换行符
  4. 将字符串流转换为字符串

    cpp 复制代码
    std::string result = ss.str();
  5. 从字符串初始化字符串流

    cpp 复制代码
    std::string input = "123 456";
    std::stringstream ss(input);
    int a, b;
    ss >> a >> b;  // a = 123, b = 456
  6. 清空字符串流

    cpp 复制代码
    ss.str("");  // 清空内容
    ss.clear();  // 重置状态标志

示例代码

下面是一个简单的示例,展示了如何使用 std::stringstream

cpp 复制代码
#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
*/

这个示例展示了如何创建字符串流、插入数据、提取数据以及将字符串流转换为字符串。

相关推荐
AA陈超3 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-14 属性菜单 - 文本值行
c++·游戏·ue5·游戏引擎·虚幻
云知谷3 小时前
【经典书籍】C++ Primer 第15章类虚函数与多态 “友元、异常和其他高级特性” 精华讲解
c语言·开发语言·c++·软件工程·团队开发
weixin_582985184 小时前
OpenCV cv::Mat.type() 以及类型数据转换
c++·opencv·计算机视觉
oioihoii6 小时前
深入理解 C++ 现代类型推导:从 auto 到 decltype 与完美转发
java·开发语言·c++
报错小能手6 小时前
项目——基于C/S架构的预约系统平台 (1)
开发语言·c++·笔记·学习·架构
lingran__6 小时前
算法沉淀第十天(牛客2025秋季算法编程训练联赛2-基础组 和 奇怪的电梯)
c++·算法
oioihoii8 小时前
当无符号与有符号整数相遇:C++中的隐式类型转换陷阱
java·开发语言·c++
Yupureki8 小时前
从零开始的C++学习生活 13:红黑树全面解析
c语言·数据结构·c++·学习·visual studio
2401_876221348 小时前
Euler
c++·数学·算法
赵杰伦cpp10 小时前
C++的继承机制精讲
java·开发语言·c++·后端