C++ How to wprintf an int as wstring

158 Views Asked by At

I have the following code. I want it to print the letter A but it gives me 65.

How do I wprintf the wchar/wstring of this number?

  int aa=65;
  std::wstring ws65 = std::to_wstring(aa);
  wprintf(L"   ws65 = %ls \n", ws65.c_str());
3

There are 3 best solutions below

8
John Zwinck On BEST ANSWER

You don't need to convert to string first, just do this:

int aa=65;
wprintf(L"   ws65 = %c \n", aa);

That's much more efficient, as you avoid an extra string allocation, construction, and copy.

Or if you want to use wcout, which is the "more C++" way:

std::wcout <<  L"   ws65 = " << static_cast<wchar_t>(aa) << std::endl;
0
Brian61354270 On

If you want to convert an int to a single-character std::wstring, you can just use std::wstring's constructor instead of std::to_wstring:

#include <iostream>
#include <string>


int main() {
    int aa = 65;
    std::wstring ws65 = std::wstring(1, aa);
    std::wcout <<  L"   ws65 = " << ws65 << L'\n';
}

which outputs

ws65 = A
0
Tiger Ros On

std::to_wstring() just converts the input into the actual written out number (ie: 123 becomes "123"). printf() and wprintf() are nice because they look at the data you give it in whatever way you specify, so since the actual binary for 'A' and the number 65 are the same, you can just tell it to read the data as a character, no conversions necessary:

int aa=65;
wprintf(L"   ws65 = %lc \n", aa);