C++ stringstream的使用 类型转换以及字符分离(功能类似split)

参考:

http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html


###################################################



//
//ostringstream, istringstream, stringstream使用
//各种基础类型转换
//
/

#include <iostream>
#include <sstream>
using namespace std;


//模版,用于stingstream和int/float/double等类型的转换
template<class out_type,class in_value>
out_type convert(const in_value & t)
{
	stringstream stream;
	
	stream<<t;//向流中传值
	out_type result;//这里存储转换结果
	stream>>result;//向result中写入值

	return result;
}

int main(int argc, char* argv[])
{
	//int转string
	int temp1_num=100;
	string temp1_str=convert<string>(temp1_num);
	cout<<temp1_str<<endl;

	//string转int
	string temp2_str="121";
	int temp2_int=convert<int>(temp2_str);
	cout<<temp2_int<<endl;

	//float(double)转string
	float temp3_num=100.32;
	string temp3_str=convert<string>(temp3_num);
	cout<<temp3_str<<endl;

	//string转float(double)
	string temp4_str="322.11";
	float temp4_num=convert<float>(temp4_str);
	cout<<temp4_num<<endl;

	//stringstream用于split很方便
	string a, b, c, d;
	string lines="adfa;asdfasd;fasdf;ccc";
	stringstream line(lines);
	getline(line, a, 'f');
	getline(line, b, ';');
	getline(line, c, ';');
	getline(line, d);
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;
	cout<<"c = "<<c<<endl;
	cout<<"d = "<<d<<endl;

	cin.get();
	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值