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

C++11的字符串与数值间的类型转换:to_string() stoi stol stoul stoll stof stod stold

2014-11-17 09:08 1621 查看

C++类型转换 

 再也不用搞C的那一套了,再也不用什么庞大的stringstream了

string的数值转换函数

代码:
#include <string>
#include <iostream>
using namespace std;

template<typename T>
void p(const T& t)
{
cout<<t<<endl;
}
int main()
{
long long ll = 1000;
string str;

str = std::to_string(ll);
p(str);

ll = stoll(str);
p(ll);

long double d = 3.141592;
str = to_string(d);
p(str);

d = stold(str);
p(d);
};
1000

1000

3.14159

3.14159

请按任意键继续. . .


全部函数如下:http://www.cplusplus.com/reference/string/



boost::lexical_cast

由于效率的问题,不建议使用,参考boost::lexical_cast

old版本(不建议使用,自己造轮子)

代码:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;

template<typename Result,typename Para>
Result lexical_cast(Para para)
{
stringstream ss;
ss<<para;
Result result;
ss>>result;
return result;
}
//int ACE_TMAIN(int argc, ACE_TCHAR *argv[])
int main(int argc, char *argv[])
{

double arr[10] = {0.1,1.2,2.3,3.4,4.5,5.6,6.7,7.8,8.9,9.0};
vector<string> str_arr;
for (size_t i =0 ; i< sizeof(arr)/sizeof(double) ; ++i)
{
str_arr.push_back(lexical_cast<string>(arr[i]));
}
ostream_iterator<string> out(cout," ");
copy(str_arr.begin(),str_arr.end(),out);

return 0;
}


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