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

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

相关推荐
Tri_Function3 小时前
动态规划DP1(c++)
c++
清水迎朝阳6 小时前
客户端软件 — 用户统计方案
服务器·c++·客户端·用户统计
再卷也是菜7 小时前
C++17(下)
c++
alexwang2117 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树
程序员zgh7 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
皓月斯语9 小时前
B2132 素数对
c++·算法·题解
星轨初途10 小时前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
笨鸟先飞的橘猫10 小时前
c++面向对象编程
开发语言·c++
啦啦啦啦啦zzzz11 小时前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
-森屿安年-11 小时前
647. 回文子串
c++·算法·动态规划