#include <locale> // wstring_convert
#include <codecvt> // codecvt_utf8
#include <iostream> // cout
#include <string> // stoi and u32string
int main() {
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
std::u32string str = U"14";
std::cout << std::stoi(convert.to_bytes(str));
}
This depends on UTF-8 and the "C" locale using the same representation for digits.
GCC's standard library implementation libstdc++ does not include the codecvt header or std::wstring_convert yet. libc++ does include both of these, as does Visual Studio's standard library implementation. If you have to use libstdc++ you may find it easiest to just implement a simple conversion function yourself.
#include <algorithm> // transform
#include <iterator> // begin, end, and back_inserter
std::string u32_to_ascii(std::u32string const &s) {
std::string out;
std::transform(begin(s), end(s), back_inserter(out), [](char32_t c) {
return c < 128 ? static_cast<char>(c) : '?';
});
return out;
}
int u32toi(std::u32string const &s) { return stoi(u32_to_ascii(s)); }
codecvt
is not yet implemented for clang and gcc ... How can I solve this problem in such situation? – Kimberliekimberlin