前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++ stringstream ss()[通俗易懂]

c++ stringstream ss()[通俗易懂]

作者头像
全栈程序员站长
发布2022-08-31 17:01:50
1.1K0
发布2022-08-31 17:01:50
举报

大家好,又见面了,我是你们的朋友全栈君。

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

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

代码语言:javascript
复制
// swapping ostringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream

int 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全部单词打印出来

代码语言:javascript
复制
#include <iostream>
#include <sstream>

using namespace std;

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

	return 0;
}

OUTPUT:

在这里插入图片描述
在这里插入图片描述

二、支持C风格的串流的输入输出操作

代码语言:javascript
复制
#include <iostream>
#include <sstream>

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/

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/143033.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、从string对象str中读取字符。遇空格结束
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档