0

I'm trying to convert a wchar_t to a hexadecimal and then convert it to std::string.

Here is my code:

#ifdef _DEBUG
    std::clog << wchar << std::endl;
#endif

    wchar_t wideChar = printf("0x%x", wchar);

#ifdef _DEBUG
    std::clog << wideChar << std::endl;
#endif

    std::string str = "";
    str.assign(wideChar, 4);

#ifdef _DEBUG
    std::clog << str << std::endl;
#endif

wchar is a variable of type wchar_t and it has a dynamic value. I'm using the value 69 in this example which is the equivalent of the E key.

First I'm converting the wchar to another wchar_t and this wideChar holds the hexadecimal value. This works like expected except it has one more character I don't need/want.

At the end I'm trying to convert the wide char to string and this fails horribly. The idea behind this is I only need the first 4 letters of the hexadecimal number (like 0x45 not 0x454).

Example Output:

69
0x454
♦♦♦♦

The biggest problem I have is that the string only has this weird symbols in it. I want to convert the wchar to string exactly how it is but I want to remove the last character.

The desired output should be:

69
0x454
0x45

Can someone tell me what my code is doing wrong and how I can do it right. Thanks in advance.

1 Answers1

0

This:

str.assign(wideChar, 4);

uses this overload:

constexpr basic_string& assign( size_type count, CharT ch );

Since you assigned the number of characters transmitted to stdout in

wchar_t wideChar = printf("0x%x", wchar);

to wideChar, then wideChar is 4 (0x45 makes it 4 characters).

So, you assign four char(4)s to the string, making it "\004\004\004\004".

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108