C/C++標準ライブラリprintf
/wprintf
関数ファミリでワイド文字列(wchar_t
型)を出力する場合、書式指定には常に%ls
を利用する。マルチバイト文字列(char
型)に対しては、常に%s
を利用する。出力先ストリームのバイト指向/ワイド指向(→id:yohhoy:20120825)と異なる場合は、wcrtomb
/mbrtowc
関数呼び出し相当による変換処理が行われる。
#include <stdio.h> #include <wchar.h> char mbsz[] = "Multibyte String"; wchar_t wsz[] = L"Wide String"; printf("%s", mbsz); // マルチバイト文字列をそのまま出力 printf("%ls", wsz); // wcrtomb関数で変換後に出力 // または wprintf(L"%s", mbsz); // mbrtowc関数で変換後に出力 wprintf(L"%ls", wsz); // ワイド文字列をそのまま出力
C99(N1256) 7.19.6.1/p8, 7.24.2.1/p8より一部引用。
7.19.6.1 The
fprintf
functionThe conversion specifiers and their meanings are:
(snip)
s
- If no
l
length modifier is present, the argument shall be a pointer to the initial element of an array of character type. Characters from the array are written up to (but not including) the terminating null character. (snip)
If anl
length modifier is present, the argument shall be a pointer to the initial element of an array ofwchar_t
type. Wide characters from the array are converted to multibyte characters (each as if by a call to thewcrtomb
function, with the conversion state described by anmbstate_t
object initialized to zero before the first wide character is converted) up to and including a terminating null wide character. The resulting multibyte characters are written up to (but not including) the terminating null character (byte). (snip)
7.24.2.1 The
fwprintf
functionThe conversion specifiers and their meanings are:
(snip)
s
- If no
l
length modifier is present, the argument shall be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state. Characters from the array are converted as if by repeated calls to thembrtowc
function, with the conversion state described by anmbstate_t
object initialized to zero before the first multibyte character is converted, and written up to (but not including) the terminating null wide character. (snip)
If anl
length modifier is present, the argument shall be a pointer to the initial element of an array of wchar_t type. Wide characters from the array are written up to (but not including) a terminating null wide character. (snip)
関連URL