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

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);
};
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;
}



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值