C ++:宽字符输出不正确? [英] C++: wide characters outputting incorrectly?

查看:216
本文介绍了C ++:宽字符输出不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码基本上是这样:

My code is basically this:

wstring japan = L"日本";
wstring message = L"Welcome! Japan is ";

message += japan;

wprintf(message.c_str());

我想使用宽字符串,但我不知道它们是如何输出的,所以我使用wprintf。当我运行如:

I'm wishing to use wide strings but I do not know how they're outputted, so I used wprintf. When I run something such as:

./widestr | hexdump

十六进制代码点创建:

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  ?  ?

为什么他们都按顺序跳?我的意思是如果wprintf是错误的,我仍然不明白为什么它会输出这样一个特定的混乱秩序!

Why are they all jumped in order? I mean if the wprintf is wrong I still don't get why it'd output in such a specific jumbled order!

edit:endianness或什么?他们似乎旋转每两个字符。 huh。

edit: endianness or something? they seem to rotate each two characters. huh.

编辑2:我试过使用wcout,但它输出完全相同的十六进制码点。很奇怪!

EDIT 2: I tried using wcout, but it outputs the exact same hexidecimal codepoints. Weird!

推荐答案

您需要定义区域设置

    #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;
    }

按预期工作(即将宽字符串转换为窄UTF-8并打印)。

Works as expected (i.e. convert wide string to narrow UTF-8 and print it).

当您将全局语言环境定义为时 - 您设置系统语言环境(如果它是UTF-8,
将打印为UTF- 8 - 即wstring将被转换)

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)

编辑:忘记我对sync_with_stdio的说明 - 这是不正确的, 。不需要。

forget what I said about sync_with_stdio -- this is not correct, they are synchronized by default. Not needed.

这篇关于C ++:宽字符输出不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆