本文介绍了如何将std :: wstring转换为数字类型(int,long,float)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将std :: wstring转换为数字类型(例如int,long,float或double)的最佳方法是什么?

解决方案

p>使用:

  #include< boost / lexical_cast.hpp> 

std :: wstring s1(L123);
int num = boost :: lexical_cast< int>(s1);

std :: wstring s2(L123.5);
double d = boost :: lexical_cast< double>(s2);

这些会抛出一个 boost :: bad_lexical_cast



另一个选项是使用Boost Qi(Boost.Spirit的子库):

  #include< boost / spirit / include / qi.hpp> 

std :: wstring s1(L123);
int num = 0;
if(boost :: spirit :: qi :: parse(s1.begin(),s1.end(),num))
; // conversion successful

std :: wstring s2(L123.5);
double d = 0;
if(boost :: spirit :: qi :: parse(s1.begin(),s1.end(),d))
; // conversion successful

使用Qi比lexical_cast更快,但会增加你的编译时间。 >

What's the best way to convert std::wstring to numeric type, such as int, long, float or double?

解决方案

Either use boost::lexical_cast<>:

#include <boost/lexical_cast.hpp>

std::wstring s1(L"123");
int num = boost::lexical_cast<int>(s1);

std::wstring s2(L"123.5");
double d = boost::lexical_cast<double>(s2);

These will throw a boost::bad_lexical_cast exception if the string can't be converted.

The other option is to use Boost Qi (a sublibrary of Boost.Spirit):

#include <boost/spirit/include/qi.hpp>

std::wstring s1(L"123");
int num = 0;
if (boost::spirit::qi::parse(s1.begin(), s1.end(), num))
    ; // conversion successful

std::wstring s2(L"123.5");
double d = 0;
if (boost::spirit::qi::parse(s1.begin(), s1.end(), d))
    ; // conversion successful

Using Qi is much faster than lexical_cast but will increase your compile times.

这篇关于如何将std :: wstring转换为数字类型(int,long,float)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:11