How can you cast between wchar_t* and an int?
I have a function which returns the inner text of an xml element. It returns it, however, as a const wchar_t*
. I wish to return this value as 开发者_Python百科an integer (And a float in some other cases). What is the best method for doing so?
The C++ way would be:
wchar_t* foo = L"123";
std::wistringstream s(foo);
int i = 0;
s >> i;
With Boost, you could do:
try {
int i2 = boost::lexical_cast<int>(foo);
} catch (boost::bad_lexical_cast const&) {
...
}
Depending on which CRT implementation you're using you may have "wide" atoi
/strtol
functions:
int i = _wtoi(foo);
long l = _wcstol(foo, NULL, 10);
1) manual parsing (using sprintf
& atof
/atoi
for instance)
2) using boost::lexical_cast
(see http://www.boost.org/doc/libs/1_40_0/libs/conversion/lexical_cast.htm)
3) using string streams (http://www.cplusplus.com/reference/iostream/ostringstream/)
精彩评论