I am trying to convert wstring_view
to int
. Is there something like stoi
that works on wstring_view
instead of string
? Can't use any C-api's since it's not necessarily null-terminated. Can't use from_chars
since it's wchar_t
. So far, I've been converting to std::wstring
, then converting to int
(using stoi
), which is probably OK with small string optimizations and all, but goes against the point of using views in the first place.
Probably the easiest approach from a coding perspective would be to use Boost's lexical_cast
(see doc) if available:
#include <boost/lexical_cast.hpp>
[[nodiscard]] int parseInt(std::wstring_view const string)
{
return boost::lexical_cast<int>(string.data(), string.size());
}
Note that this will throw boost::bad_lexical_cast
if string
cannot be parsed in its entirety. This is different to std::stoi
, std::strtol
, atoi
and the like. See this on Coliru
To avoid exceptions one could use try_lexical_convert()
as described here.
When it comes to performance they have their own stats which seem to indicate that for string to integral conversion it is faster than std::scanf()
or std::stringstream
.