#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 s number!";
throw(s);
}
return(d);
}
int main(int argc, _TCHAR* argv[])
{
int i;
try
{
cout << sciToDub("1.234e-02") << endl;
cout << sciToDub("-1.234e-02") << endl;
}
catch(string & e)
{
cout << e << endl;
}
cin >> i;
return 0;
}
改为模版:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template<typename T>
T sciToDub(const string & str)
{
stringstream ss(str);
T d = 0;
ss >> d;
if(ss.fail())
{
string s = "Unable to format";
s += str;
s += "as s number!";
throw(s);
}
return(d);
}
int main(int argc, _TCHAR* argv[])
{
int i;
try
{
cout << sciToDub<double>("1.234e-02") << endl;
cout << sciToDub<double>("-1.234e-02") << endl;
}
catch(string & e)
{
cout << e << endl;
}
cin >> i;
return 0;
}