原文:http://blog.163.com/zhuandi_h/blog/static/180270288201291710222975/
使用stringstream对象简化类型转换
C++标准库中的
为什么要学习
如果你已习惯了
int n=10000;
chars[10];
sprintf(s,”%d”,n);// s中的内容为“10000”
到目前为止看起来还不错。但是,对上面代码的一个微小的改变就会使程序崩溃:
int n=10000;
char s[10];
sprintf(s,”%f”,n);// 看!错误的格式化符
在这种情况下,程序员错误地使用了%f格式化符来替代了%d。因此,s在调用完sprintf()后包含了一个不确定的字符串。要是能自动推导出正确的类型,那不是更好吗?
由于n和s的类型在编译期就确定了,所以编译器拥有足够的信息来判断需要哪些转换。
你的编译器支持
注意,
string到int的转换
string result=”10000”;
int n=0;
stream<>n;//n等于10000
重复利用stringstream对象
template
void to_string(string & result,const T& t)
{
ostringstream oss;//创建一个流
oss<
这样,你就可以轻松地将多种数值转换成字符串了:
to_string(s1,10.5);//double到string
to_string(s2,123);//int到string
to_string(s3,true);//bool到string
可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:
template
out_type convert(const in_value & t)
{
stringstream stream;
stream<>result;//向result中写入值
return result;
}
这样使用convert():
double d;
string salary;
string s=”12.56”;
d=convert(s);//d等于12.56
salary=convert(9000.0);//salary等于”9000”
结论
#include
#include
#include
int main()
{
std::stringstream stream;
std::string result;
int i = 1000;
stream << i; //将int输入流
stream >> result; //从stream中抽取前面插入的int值
std::cout << result << std::endl; // print the string "1000"
}
#include
#include
int main()
{
std::stringstream stream;
char result[8] ;
stream << 8888; //向stream中插入8888
stream >> result; //抽取stream中的值到result
std::cout << result << std::endl; // 屏幕显示 "8888"
}
例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear().
#include
#include
int main()
{
std::stringstream stream;
int first, second;
stream<< "456"; //插入字符串
stream >> first; //转换成int
std::cout << first << std::endl;
stream.clear(); //在进行多次转换前,必须清除stream
stream << true; //插入bool值
stream >> second; //提取出int
std::cout << second << std::endl;
}