c++ - en_US.UTF-8 区域设置的 Windows 等效项是什么?

标签 c++ windows unicode utf-8 locale

如果我想在 Windows 上执行以下操作,正确的语言环境是什么以及我如何检测它是否实际存在: Does this code work universaly, or is it just my system?

最佳答案

虽然对命名语言环境没有很好的支持,但 Visual Studio 2010 确实包含 C++11 所需的 UTF-8 转换方面:std::codecvt_utf8 for UCS2 和 std::codecvt_utf8_utf16 用于 UTF-16:

#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
void prepare_file()
{
    // UTF-8 data
    char utf8[] = {'\x7a',                       // latin small letter 'z' U+007a
                   '\xe6','\xb0','\xb4',         // CJK ideograph "water"  U+6c34
                   '\xf0','\x9d','\x84','\x8b'}; // musical sign segno U+1d10b
    std::ofstream fout("text.txt");
    fout.write(utf8, sizeof utf8);
}
void test_file_utf16()
{
    std::wifstream fin("text.txt");
    fin.imbue(std::locale(fin.getloc(), new std::codecvt_utf8_utf16<wchar_t>));
    std::cout << "Read from file using UTF-8/UTF-16 codecvt\n";
    for(wchar_t c; fin >> c; )
        std::cout << std::hex << std::showbase << c << '\n';
}
void test_file_ucs2()
{
    std::wifstream fin("text.txt");
    fin.imbue(std::locale(fin.getloc(), new std::codecvt_utf8<wchar_t>));
    std::cout << "Read from file using UTF-8/UCS2 codecvt\n";
    for(wchar_t c; fin >> c; )
        std::cout << std::hex << std::showbase << c << '\n';
}
int main()
{
    prepare_file();
    test_file_utf16();
    test_file_ucs2();
}

这个输出,在我的 Visual Studio 2010 EE SP1 上

Read from file using UTF-8/UTF-16 codecvt
0x7a
0x6c34
0xd834
0xdd0b
Read from file using UTF-8/UCS2 codecvt
0x7a
0x6c34
0xd10b
Press any key to continue . . .

关于c++ - en_US.UTF-8 区域设置的 Windows 等效项是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45629093/

相关文章:

java - PDFBox hasGlyph() 为不支持的 unicode 控制字符返回 true

ruby-on-rails - 处理 ruby​​ 1.8.7 中不同类型的 utf 连字符

c++ - 如何使用 operator<< 将文件对象提供给使用 << 的类?

c++ - 以纳秒为单位计算时间的代码

c++ - 循环/方法太慢

c++ - C++0x 标准如何定义 C++ Auto 多重声明?

c++ - 如何使用 Application Verifier 查找内存泄漏

windows - 如何阅读 Windows 10 BSOD 迷你转储分析

windows - 如何在Windows XP Embedded(未安装Sc.exe)上创建服务?

python - 在 Python 中生成随机 UTF-8 字符串