yohhoyの日記

技術的メモをしていきたい日記

書式指定%lsとwchar_t型

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 function

The 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 an l 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 converted to multibyte characters (each as if by a call to the wcrtomb function, with the conversion state described by an mbstate_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 function

The 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 the mbrtowc function, with the conversion state described by an mbstate_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 an l 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