What's the difference between printf("%s"), printf("%ls"), wprintf("%s"), and wprintf("%ls")?

Display Name picture Display Name · Nov 8, 2014 · Viewed 37.9k times · Source

Consider this sample program:

#include <cstdio>
#include <cwchar>
#include <string>

int main()
{
    std::string narrowstr = "narrow";
    std::wstring widestr = L"wide";
    printf("1 %s \n", narrowstr.c_str());
    printf("2 %ls \n", widestr.c_str());
    wprintf(L"3 %s \n", narrowstr.c_str());
    wprintf(L"4 %ls \n", widestr.c_str());

   return 0;
}

The output of this is:

1 narrow 
2 wide 

I'm wondering:

  1. why 3 & 4 didn't print
  2. what the differences are between 1&3, and 2&4.
  3. does it make any difference if narrowstr is in utf8 and widestr is in utf16?

Answer

Ajay picture Ajay · Nov 8, 2014

You need to do:

wprintf(L"3 %hs \n", narrowstr.c_str());
wprintf(L"4 %s \n", widestr.c_str());

Why? Because for printf, %s says narrow-char-string. For wprintf, %ls says wide.

But, for wprintf, %s implies wide, %ls would mean wide itself. %hs would mean narrow (for both). For printf, %s, in this manner would simply mean %hs

On VC++/Windows, %S (capital S), would reverse the effect. Therfore for printf("%S") it would mean wide, and wprintf("%S") would mean narrow. This is useful for _tprintf.