C++ How to get the std::wstring of a int value?

134 Views Asked by At

I have an int val = 0x1234; and want to get the std::wstring (ሴ)of that number

int val = 0x1234;
std::wstring wstr =  to_wstring(val) ( this gives me L"4660" which is not what I want !)
std::wstring wstr_OK =  ????         ( it should give me the character ሴ)
1

There are 1 best solutions below

4
wohlstad On

std::to_wstring (as well as std::to_string) is creating a string representation of a value.
In case of an int it will create a string where each digit is converted into a character that represent it.
For example 1 will be represented as the character '1' (which has a different numeric value - e.g. 49 if this was ascii).

In your case you already know the numeric value of the desired character, so you can simply assign the element of your wstring with it:

std::wstring wstr;
wstr.resize(1);    
wstr[0] = val;

Or more simply:

std::wstring wstr(1, val);

Note:
The solution above assumes in general that the numeric value can be indeed stored in one wstring element, i.e. wchar_t. This seems to be the case for the specific code that you used (0x1234).
For more info see: Convert unicode codepoint to utf-16.