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

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

相关推荐
孞㐑¥3 小时前
Linux之Socket 编程 UDP
linux·服务器·c++·经验分享·笔记·网络协议·udp
水木兰亭6 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
CoderCodingNo7 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法
秋风&萧瑟9 小时前
【C++】C++中的友元函数和友元类
c++
梁诚斌9 小时前
使用OpenSSL接口读取pem编码格式文件中的证书
开发语言·c++
2301_8035545213 小时前
c++中的绑定器
开发语言·c++·算法
海棠蚀omo14 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记
消失的旧时光-194314 小时前
c++ 的标准库 --- std::
c++·jni
GiraKoo14 小时前
【GiraKoo】C++11的新特性
c++·后端
不午睡的探索者15 小时前
告别性能瓶颈!Python 量化工程师,进击 C++ 高性能量化交易的“必修课”!
c++·github