码迷,mamicode.com
首页 > 其他好文 > 详细

使用stringstream格式化字符串

时间:2015-03-28 08:45:14      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

stringstream所在头文件为<sstream>

一般有如下常用功能:

1、安全格式化字符串

stringstream常用来安全的格式化若干个字符串,数值到一个缓冲区, 而不用担心溢出, 可以用来取代sprintf.

注:使用stringstream 将int or double 等类型转换成string,如果你想要转换多个int/double等类型的变量,而又始终用一个stringstream对象(避免总是创建stringstream的开销),那么你就需要在再一次用stringstream之前将stringstream的内容清空,

方法为:

sringstream ss;

ss.str("");

	stringstream ss;
	int a = 100;
	double b = 100.2;

	ss << std::fixed << std::setprecision(2);
	ss << a << " " << b;
	cout << ss.str() << endl;
	ss.str("");
	ss << 100;
	cout << ss.str();

2、读取字符串,转换成对应的数值变量

类似atoi atof函数的功能

string str("100.202");
stringstream ss1(str);
double c;
ss1 >> c;
cout << c << endl;

 

使用stringstream格式化字符串

标签:

原文地址:http://www.cnblogs.com/cmranger/p/4373558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!