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
*/

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

相关推荐
johnZhangqi5 小时前
深圳大学-计算机信息管理课程实验 C++ 自考模拟题
java·开发语言·c++
StudyWinter6 小时前
【C++】仿函数和回调函数
开发语言·c++·回调函数·仿函数
君鼎7 小时前
Effective C++ 条款55:熟悉Boost库
c++
Zafir20248 小时前
Qt实现TabWidget通过addTab函数添加的页,页内控件自适应窗口大小
开发语言·c++·qt·ui
阿巴~阿巴~8 小时前
深入解析C++非类型模板参数
开发语言·c++
多吃蔬菜!!!9 小时前
vscode 搭建C/C++开发环境搭建(linux)
linux·c语言·c++
小指纹11 小时前
河南萌新联赛2025第(六)场:郑州大学
java·开发语言·数据结构·c++·算法
岁忧11 小时前
(nice!!!)(LeetCode 每日一题) 1277. 统计全为 1 的正方形子矩阵 (动态规划)
java·c++·算法·leetcode·矩阵·go·动态规划
咔咔咔的11 小时前
679. 24 点游戏
c++
the sun3412 小时前
Reactor设计模式及其在epoll中的应用
linux·运维·服务器·c++