stringstream中的.clear()和.str()

在C++中可以使用stringstream来很方便的进行类型转换,字符串串接,不过注意重复使用同一个stringstream对象时要先继续清空,而清空很容易想到是clear方法,而在stringstream中这个方法实际上是清空stringstream的状态(比如出错等),真正清空内容需要使用.str(“”)方法。

.str(“”)方法可以清楚缓存,但是,需要重复使用同一个stringstream对象时,得先用.str(“”)方法清楚缓存,再用.clear()方法重设状态,否则对stringstream对象的操作是无效的。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
	stringstream stream;
	stream<<"123";
	int n;
	stream>>n;
	cout<<n<<endl;
	//stream.str("");
	stream.clear();
	stream<<"de";
	string s;
	stream>>s;
	cout<<s;
	return 0;
}

输出结果:


而不用.str(“”)方法,只用.clear()方法,可以得到同上的结果,但是这是很危险的,极有可能耗尽全部内存。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
	stringstream stream;
	stream<<"123";
	int n;
	stream>>n;
	cout<<n<<endl;
	stream.str("");
	//stream.clear();
	stream<<"de";
	string s;
	stream>>s;
	cout<<s;
	return 0;
}


#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
	stringstream stream;
	stream<<"123";
	int n;
	stream>>n;
	cout<<n<<endl;
	//stream.str("");
	//stream.clear();
	stream<<"de";
	string s;
	stream>>s;
	cout<<s;
	return 0;
}






  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值