c++ stringstream ss()

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

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

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

#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风格的串流的输入输出操作

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

  • 29
    点赞
  • 109
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WeSiGJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值