I want to convert a char16_t to an integer and/or a long.
const char16_t* t = u"12";
long lt = atol( t);
Does such a function not exist?
Try this function: (it's not necessarily the most efficient solution, but it gets the job done if you have no choice (i.e. you have to have a char16_t*
as input) and you're sure that you actually have a valid sequence of digits in your char16_t*
string)
#include <codecvt>
#include <locale>
#include <string>
int char16_to_int(const char16_t* s16)
{
// https://stackoverflow.com/a/7235204/865719
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
std::string str = convert.to_bytes(s16);
return std::stoi(str);
}
long char16_to_long(const char16_t* s16)
{
// https://stackoverflow.com/a/7235204/865719
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
std::string str = convert.to_bytes(s16);
return std::stol(str);
}
EDIT: I've refactored the solution just a little bit to reduce repetition:
#include <codecvt>
#include <locale>
#include <string>
std::string char16_to_string(const char16_t* s16)
{
// https://stackoverflow.com/a/7235204/865719
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.to_bytes(s16);
}
long char16_to_long(const char16_t* s16)
{
return stol(char16_to_string(s16));
}
int char16_to_int(const char16_t* s16)
{
return stoi(char16_to_string(s16));
}