Locale の罠
コンソールでマルチバイト文字を使う。
#include <stdio.h> #include <tchar.h> int _tmain(int argc, TCHAR* argv[]) { _tprintf(_T("%s\n"), _T("こんにちは、世界!")); return 0; }
で、こいつを実行してみると。
>cl /D_UNICODE /DUNICODE hello.cc Microsoft(R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. hello.cc Microsoft (R) Incremental Linker Version 8.00.50727.762 Copyright (C) Microsoft Corporation. All rights reserved. /out:hello.exe hello.obj >hello ????????!
お前は何を言っているんだ。
答えから言うと、コンソールアプリの場合は setlocale() が必要らしい。
LC_CTYPE の部分が C になっていて、ワイド文字からマルチバイト文字への変換で EILLSEQ でエラーが出ているために「?」になるようです。
ちなみに、プログラムがマルチバイト文字セットを利用する場合はこの問題は発生しないみたい。
ちゃんと動くプログラム。
#include <stdio.h> #include <tchar.h> #include <locale.h> int _tmain(int argc, TCHAR* argv[]) { setlocale(LC_ALL, ""); _tprintf(_T("%s\n"), _T("こんにちは、世界!")); return 0; }
>hello こんにちは、世界!