如何使用std::wcout
打印std::wstring
?如何将C++ wstring UTF-8字符打印到Mac OS或Unix终端?
我尝试以下,这是推荐here,但它仅适用于打印此¡Hola!
但不是这个日本
:
#include <iostream>
#include <clocale>
int main(int argc, char* argv[])
{
char* locale = setlocale(LC_ALL, "");
std::cout << "locale: " << locale << std::endl; // "C" for me
std::locale lollocale(locale);
setlocale(LC_ALL, locale);
std::wcout.imbue(lollocale);
std::wcout << L"¡Hola!" << std::endl; // ok
std::wcout << L"日本" << std::endl; // empty :(
return 0;
}
还有以下(这是推荐here)不会在打印日文字符全部:
#include <stdio.h>
#include <string>
#include <locale>
#include <iostream>
using namespace std;
int main()
{
std::locale::global(std::locale(""));
wstring japan = L"日本";
wstring message = L"Welcome! Japan is ";
message += japan;
wprintf(message.c_str());
wcout << message << endl;
}
所有这些都在Mac OS 10.6.8上。使用g ++ 4.2.1,使用终端2.1.2。
终端一般可以显示字符,例如当我的源代码为cat
时。此外,这个命令工作正常cout << "日本" << std::endl;
,但我确实需要打印wstring
。
我$LANG
是这样的:
$ echo $LANG
en_US.UTF-8
这不会有帮助,但这里是Mac OSX的猫的源代码:http://www.freebsd.org/cgi/cvsweb.cgi/src/bin/cat/cat.c?rev= 1.33.2.1.8.1; content-type = text%2Fx-cvsweb-markup – Wug 2012-07-16 21:19:32
'wstring'不会是UTF-8。希望你的编译器将UTF-8源码转换为宽字符常量。 – 2012-07-16 21:22:58
也许这个问题很有用http://stackoverflow.com/questions/148403/utf8-to-from-wide-char-conversion-in-stl – 2012-07-16 21:46:39