1

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Post Self
  • 1,471
  • 2
  • 14
  • 34
  • 1
    In which encoding do you want it? – Biffen Apr 25 '16 at 14:02
  • The first two don't work because `\u` is a compile-time operation, not a runtime operation. You need to provide more information on what happens in the third case. What is the value of `wc`? Is it possible that your `wcout` simply doesn't support that character? – Raymond Chen Apr 25 '16 at 14:15
  • Huh, I have not thought aout that. I tried encoding with UTF8 now and in Windows I just get weird characters when doing `std::cout << "\u265A"`, namely `♚`. I'll have to read a bit into this. But some encoding that works on Windows. @Biffen – Post Self Apr 25 '16 at 14:16
  • Well, the problem is, that I don't know any other way of checking the value of `wc`, other that `std::wcout`, but the documentation of `strtol` suggests it should do what it is supposed to do. Also what do you mean, by not able to output? 265A is pretty high up, so that might be a possibility, but how do I bypass it? @RaymondChen – Post Self Apr 25 '16 at 14:20
  • @kim366 have you considered that perhaps your console does not support UTF-8? – eerorika Apr 25 '16 at 14:21
  • Try using a debugger. The default locale for `wcout` in Windows is the "C" locale, which as I recall does not support characters above 255. – Raymond Chen Apr 25 '16 at 14:22
  • it does. http://stackoverflow.com/questions/19955385/utf-8-in-windows-7-cmd @user2079303 – Post Self Apr 25 '16 at 14:24
  • Thank you! I did use a debugger and it said "Expression expected" (my translation), so I will look into that. – Post Self Apr 25 '16 at 14:36
  • 1
    @kim366 What are you talking about? Back then you didn't even know what a debugger was.. – Post Self Aug 14 '17 at 17:17

1 Answers1

1

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;
Toby Speight
  • 27,591
  • 48
  • 66
  • 103