c++ - What's the difference between printf("%s"), printf("%ls"), wprintf("%s"), and wprintf("%ls")? -
consider 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()); homecoming 0; }
the output of is:
1 narrow 2 wide
i'm wondering:
why 3 & 4 didn't print what differences between 1&3, , 2&4. does create difference if narrowstr in utf8 , widestr in utf16?
note you're using c streams. c streams have special quality called "orientation". stream either unoriented, wide, or narrow. orientation decided first output made particular stream (see http://en.cppreference.com/w/cpp/io/c summary of c i/o streams)
in case, stdout
starts out unoriented, , executing first printf
, you're setting narrow. 1 time narrow, it's stuck narrow, , wprintf
fails (check homecoming code!). way alter c stream freopen
it, doesn't quite work stdout. that's why 3 , 4 didn't print.
the differences between 1 , 3 1 narrow output function using narrow string conversion specifier %s: reads bytes char array , sends bytes byte stream. 3 wide output function narrow string conversion specifier %s: first reads bytes char array , mbtowc
s them wchar_t
s, sends wchar_t
s wide stream, wctomb
s them bytes or multibyte sequences pushed standard out write
finally, if widestr in utf16, must using windows, , bets off; there little back upwards beyond ascii on platform. may give in , utilize winapi (you can standard c++11 unicode things, , c output, magic words _setmode(_fileno(stdout), _o_u16text);
, that's been discussed plenty times)
c++ unicode printf widechar
No comments:
Post a Comment