如何将std :: wstring转换为数字类型(int,long,float)?

Hyd*_*den 5 c++ types stl wstring

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

How*_*ant 33

的C++ 0x引入了以下 功能<string>:

int                stoi  (const wstring& str, size_t* idx = 0, int base = 10);
long               stol  (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long      stoul (const wstring& str, size_t* idx = 0, int base = 10);
long long          stoll (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const wstring& str, size_t* idx = 0, int base = 10);

float       stof (const wstring& str, size_t* idx = 0);
double      stod (const wstring& str, size_t* idx = 0);
long double stold(const wstring& str, size_t* idx = 0);
Run Code Online (Sandbox Code Playgroud)

idx是一个可选的空指针,指向转换结束str(由转换函数设置).


hka*_*ser 17

使用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);
Run Code Online (Sandbox Code Playgroud)

boost::bad_lexical_cast如果无法转换字符串,这些将抛出异常.

另一种选择是使用Boost Qi(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
Run Code Online (Sandbox Code Playgroud)

使用Qi比lexical_cast快得多,但会增加编译时间.

  • 人们声称C++是非常复杂的! (4认同)

rav*_*int 11

最好?

如果您不想使用除CRT库以外的任何内容,并且对于如果无法转换字符串而获得0感到满意,那么您可以节省错误处理,复杂语法,包括标题

std::wstring s(L"123.5");
float value = (float) _wtof( s.c_str() );
Run Code Online (Sandbox Code Playgroud)

这一切都取决于你在做什么.这是KISS的方式!

  • `_wtof`来自哪里? (2认同)