为什么 std::codecvt<wchar_t、char、mbstate_t> 不能按定义工作?
Why does std::codecvt<wchar_t, char, mbstate_t> not work as defined?
#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(中文字符集)。如果文档为 true,那么wcout
可以像f1()
一样将 unicode 字符串从 UCS-2 转换为 GBK;但是,事实并非如此。为什么?
您默认构造了一个std::codecvt
,没有特定的转换规则。它无法知道你想要GBK而不是GB18030或UTF-8。
获取将wchar_t转换为 GBK 的编解码器的方法:
-
为 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可能具有更合适的转换功能。
相关文章:
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- std::chrono::d uration 可以按秒初始化,但不能按毫秒初始化?
- 为什么"std::is_function_v"不能按预期工作?
- 我怎么不能按课程代码的降序对数字进行排序
- 我的代码是完整的,至少我相信它是...为什么它不能按预期运行?
- 为什么将可执行文件重命名为临时文件的此代码段不能按预期工作?
- 为什么我不能按预期初始化长篇
- c++类函数在另一个函数中不能按预期工作
- 为什么我不能按值将右值 std::stringstream 传递给函数?
- 为什么这个简单的批处理方法不能按预期工作?
- 为什么 std::is_copy_constructible 不能按预期工作
- 为什么 std::codecvt<wchar_t、char、mbstate_t> 不能按定义工作?
- 为什么不能按名称打印成员函数的地址?
- 为什么我的内联汇编程序不能按预期工作
- 这个模板"specialization"代码在做什么,为什么它可以编译但不能按预期工作?
- 创建了我自己的向量类.可以重载流运算符,但不能按值c++打印
- 如果函数参数类型是ABC,为什么不能按值传递?
- Qt不能按名称插槽,即使在objectName设置之后
- 为什么类型推导不能按预期工作
- 为什么"extern const int n;"不能按预期工作?