您的位置:首页 > 编程语言 > C语言/C++

C++中将科学计数转换为其他类型

2012-03-09 23:40 225 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: