c++ stringstream ss()
发布日期:2021-05-08 03:55:01 浏览次数:18 分类:精选文章

本文共 1494 字,大约阅读时间需要 4 分钟。

定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。本文以 stringstream 为主,介绍流的输入和输出操作。

主要用来进行数据类型转换,由于 使用 string 对象来代替字符数组(snprintf方式),就避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。简单说,相比c库的数据类型转换而言, 更加安全、自动和直接。

cplusplus官方版本:

// swapping ostringstream objects#include 
// std::string#include
// std::cout#include
// std::stringstreamint main () { std::stringstream ss; ss << 100 << ' ' << 200; int foo,bar; ss >> foo >> bar; std::cout << "foo: " << foo << '\n'; std::cout << "bar: " << bar << '\n'; return 0;} Edit & Run

Output:

foo: 100
bar: 200

一、从string对象str中读取字符。遇空格结束

下面代码增加while循环,能将str全部单词打印出来

#include 
#include
using namespace std;int main(){ string str = "hello world"; cout << str << endl; stringstream ss(str); //将str复制到ss string abc; while(ss >> abc) //相当于输入一个个的单词 { cout << abc <

OUTPUT:

在这里插入图片描述
二、支持C风格的串流的输入输出操作

#include 
#include
using namespace std;int main(){ int num = 1000; string str; stringstream ss; //将str复制到ss ss << num; ss >> str; ss.clear();//使用stringstream来做转换时,最好使用完,进行ss.clear()操作 cout << str << endl; cout << str.c_str() << endl; return 0;}

OUTPUT:

在这里插入图片描述

三、字符的拼接

在这里插入图片描述

本文作者:WeSiGJ

参考链接(包括但不限于):

https://blog.csdn.net/liitdar/article/details/82598039
https://blog.csdn.net/weierqiuba/article/details/66473060
https://blog.csdn.net/xw20084898/article/details/21939811
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/

上一篇:数据同步Canal搭建全过程
下一篇:java垃圾回收机制总结

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月04日 02时36分30秒