简体   繁体   中英

How to output Unicode characters from hex string in C++?

I have a string called str containing the hex code 265A and I would like to output it as a Unicode character, which should be the black chess king.

So these are the ways I have already tried:

std::string str = "\u" + str;
std::cout << str;

but this gives me the error

error: incomplete universal character name \u

Doing

std::cout << "\u" << str;

also didn't work, for the same reason.

So I tried using wchar_t like this:

wchar_t wc = strtol(str.c_str(), NULL, 16);
std::wcout << wc;

but that just didn't output anything.

So I really don't know what else to do.

Your strtol approach is about right. The following test program tests that you can create an A this way:

#include <string>
#include <cstdlib>
#include <iostream>

int main()
{
    const std::string str = "41";

    wchar_t wc = std::strtol(str.c_str(), NULL, 16);
    std::wcout << wc << std::endl;
}

You're likely having problems with the output side of things, or your system's wchar_t is some non-Unicode type - you can demonstrate that with something like

std::wcout << wchar_t(65) << wchar_t(0x265A) << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM