What's the best way to convert std::wstring to numeric type, such as int, long, float or double?
解决方案#include
std::wstring s1(L"123");
int num = boost::lexical_cast(s1);
std::wstring s2(L"123.5");
double d = boost::lexical_cast(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
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.