为什么std :: codecvt <wchar_t,char,=“”mbstate_t =“”>不能按定义工作?</wchar_t,>

时间:2013-09-21 11:36:21

标签: c++ windows unicode character-encoding iostream

#include <iostream>

using namespace std;

void f1()
{
    wcout.imbue(locale("chs"));
    wcout << L"您" << endl;
}

void f2()
{
    locale loc(wcout.getloc(), new codecvt<wchar_t, char, mbstate_t>());

    wcout.imbue(loc);
    wcout << L"好" << endl;
}

int main()
{
    f1(); // OK
    f2(); // Error. There is no output as expected.
}

根据cplusplus.com的在线文档:

codecvt<wchar_t,char,mbstate_t>: 

    converts between native wide and narrow character sets.

该程序使用VC ++编译,并在Windows上运行。

在这个程序中,内部字符集是UCS-2,它由VC ++编译器定义;外部字符集,即窄字符集,是控制台环境中的GBK(中文字符集)。如果文档是真的,那么wcout可以将unicode字符串从UCS-2转换为GBK f1();但事实并非如此。为什么呢?

1 个答案:

答案 0 :(得分:3)

您默认构建了std::codecvt,没有特定的转化规则。它无法知道你想要GBK而不是GB18030或UTF-8。

获取将wchar_t转换为GBK的codecvt的方法:

  • 为GBK构建std::locale只需将其与您的流一起使用,无需拉出方面

    wcout.imbue(std::locale("")); // this uses the current user settings,
    wcout.imbue(std::locale("zn_CN.gbk")); // or name the locale explicitly,
                                           // by whatever name Windows calls it
    
  • 直接使用std::codecvt_byname

    构建构面
    wcout.imbue(std::locale(wcout.getloc(),
                new std::codecvt_byname("zh_CN.gbk")); // explict name
    
  • 编写您自己的转换例程并从std::codecvt派生,因此您可以将其与

    一起使用
    wcout.imbue(std::locale(wcout.getloc(), new yourcodecvt);
    

Windows对C ++语言环境的支持非常差,但WinAPI可能具有更合适的转换功能。