Joh*_* D. 7 c++ string unicode widestring widechar
我的代码基本上是这样的:
wstring japan = L"??";
wstring message = L"Welcome! Japan is ";
message += japan;
wprintf(message.c_str());
Run Code Online (Sandbox Code Playgroud)
我希望使用宽字符串,但我不知道它们是如何输出的,所以我使用了wprintf.当我运行如下的东西时:
./widestr | hexdump
Run Code Online (Sandbox Code Playgroud)
十六进制代码点创建了这个:
65 57 63 6c 6d 6f 21 65 4a 20 70 61 6e 61 69 20 20 73 3f 3f
e W c l m o ! e J p a n a i s ? ?
Run Code Online (Sandbox Code Playgroud)
为什么他们都按顺序跳了?我的意思是如果wprintf是错的,我仍然不明白为什么它会以这样一个特定的混乱顺序输出!
编辑:endianness还是什么?他们似乎旋转每两个字符.呵呵.
编辑2:我尝试使用wcout,但它输出完全相同的十六进制代码点.奇怪的!
Art*_*yom 12
You need to define locale
#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;
}
Run Code Online (Sandbox Code Playgroud)
Works as expected (i.e. convert wide string to narrow UTF-8 and print it).
When you define global locale to "" - you set system locale (and if it is UTF-8 it would be printed out as UTF-8 - i.e. wstring will be converted)
Edit: forget what I said about sync_with_stdio -- this is not correct, they are synchronized by default. Not needed.