C++类型转换
1 再也不用搞C的那一套了,再也不用什么庞大的stringstream了
string的数值转换函数
2 其中,sto*()提供了针对string和wstring的重载
代码:
#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);
};
10001000
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;
}