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

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

相关推荐
鱼子星_7 分钟前
【C++】string(上):string的基本使用
c++·笔记·字符串
神仙别闹1 小时前
编写基于C++ Huffman 算法的无损压缩程序和解压程序
java·c++·算法
炸膛坦客1 小时前
单片机/C/C++八股:(二十三)#define 和 typedef 的区别
c语言·c++·单片机
旖-旎2 小时前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
阿米亚波3 小时前
【C++ STL】std::list
c++·windows·笔记·stl·list
橙色阳光五月天3 小时前
CMake 构建配置文件解析
c++·cmake·plugin
载数而行5203 小时前
C++进阶 Linux相关的静态库,动态库,第三方库
c++
c238563 小时前
下篇:伸缩魔法!进阶吃透可变滑动窗口篇
c++·算法
来一碗刘肉面3 小时前
顺序表的按值查找
数据结构·c++·算法
小肝一下4 小时前
2. 顺序表和链表
c语言·数据结构·c++·链表·dijkstra·依蕾娜·香香的依蕾娜