In POSIX you can print UTF8 string directly:
std::string utf8 = "\xc3\xb6"; // or just u8"ö"
printf(utf8);
In Windows, you have to convert to UTF16. Use wchar_t
instead of char16_t
, even though char16_t
is supposed to be the right one. They are both 2 bytes per character in Windows.
You want convert.from_bytes
to convert from UTF8, instead of convert.to_bytes
which converts to UTF8.
Printing Unicode in Windows console is another headache. See relevant topics.
Note that std::wstring_convert
is deprecated and has no replacement as of now.
#include <iostream>
#include <string>
#include <codecvt>
#include <windows.h>
int main()
{
std::string utf8 = "\xc3\xb6";
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> convert;
std::wstring utf16 = convert.from_bytes(utf8);
MessageBox(0, utf16.c_str(), 0, 0);
DWORD count;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), utf16.c_str(), utf16.size(), &count, 0);
return 0;
}
Encoding/Decoding URL
"URL safe characters" don't need encoding. All other characters, including non-ASCII characters, should be encoded. Example:
std::string encode_url(const std::string& s)
{
const std::string safe_characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
std::ostringstream oss;
for(auto c : s) {
if (safe_characters.find(c) != std::string::npos)
oss << c;
else
oss << '%' << std::setfill('0') << std::setw(2) <<
std::uppercase << std::hex << (0xff & c);
}
return oss.str();
}
std::string decode_url(const std::string& s)
{
std::string result;
for(std::size_t i = 0; i < s.size(); i++) {
if(s[i] == '%') {
try {
auto v = std::stoi(s.substr(i + 1, 2), nullptr, 16);
result.push_back(0xff & v);
} catch(...) { } //handle error
i += 2;
}
else {
result.push_back(s[i]);
}
}
return result;
}