2007年3月14日星期三

c++食谱第三章部分笔记之四

食谱3.5 处理包含科学记数法的数字字符串
问题:
要处理的一个字符串为用科学记数法表示的数字,要转换其为double型
方案:
直接使用标准库中的stringstream类


#include<iostream>
#include<sstream>
#include<string>
using namespace std;
double sciToDub(const string&str){
stringstream ss(str);
double d=0;
ss>>d;
if(ss.fail()){
string s="Unable to format ";
s+=str;
s+=" as a number";
throw(s);
}
return d;
}
int main(){
try{
cout<<sciToDub("1.234e5")<<endl;
cout<<sciToDub("6.02e-2")<<endl;
cout<<sciToDub("asdf")<<endl;
}
catch(string&s){
cerr<<"Whoops: "<<s<<endl;
}
}


其显示的结果为:
123400
0.0602
Whoops: Unable to format asdf as a number

为了通用性,即不仅可以转换为double型,也可以转换为int,long,float型,上面的可以改写为函数模板:
<code>
template<typename T>
T strToNum(const string& str){
stringstream ss(str);
T tmp;
ss>>tmp;
if(ss.fail()){
string s="Unable to format ";
s+=str;
s+=" as a number";
throw(s);
}
return (tmp);
}
</code>
按如下方式使用:
double d=strToNum<double>("7.0");

没有评论: