wcin.imbue和UTF-8

n. *_* m. 7 c++ locale g++ utf-8 clang++

在使用g ++的linux上,如果我设置了utf8全局语言环境,那么wcin正确地将UTF-8转码为内部wchar_t编码.

但是,如果我使用经典语言环境并将UTF8语言环境灌输到wcin中,则不会发生这种情况.输入完全失败,或者每个字节独立转换为wchar_t.

使用clang ++和libc ++,既不设置全局语言环境也不设置语言环境wcin.

#include <iostream>
#include <locale>
#include <string>

using namespace std;

int main() {
    if(true)        
        // this works with g++, but not with clang++/libc++
        locale::global(locale("C.UTF-8"));
    else
        // this doesn't work with either implementation
        wcin.imbue(locale("C.UTF-8"));
    wstring s;
    wcin >> s;
    cout << s.length() << " " << (s == L"áéú");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输入流仅包含áéú字符.(它们是UTF-8,而不是任何单字节编码).

现场演示:一 两个(我不能重现在线编译器的其他行为).

这是符合标准的吗?我不应该单独留下全局区域设置imbue而是使用吗?

是否应将任何描述的行为归类为实施错误?

Rom*_*kov 4

首先,您应该将 wcout 与 wcin 一起使用。

\n\n

现在您有两种可能的解决方案:

\n\n

1) 使用以下命令停用 iostream 和 cstdio 流的同步

\n\n
   ios_base::sync_with_stdio(false);\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,这应该是第一次调用,否则行为取决于实现。

\n\n
int main() {\n\n   ios_base::sync_with_stdio(false);\n   wcin.imbue(locale("C.UTF-8"));\n\n   wstring s;\n   wcin >> s;\n   wcout << s.length() << " " << (s == L"\xc3\xa1\xc3\xa9\xc3\xba");\n   return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

2) 本地化 locale 和 wcout:

\n\n
int main() {\n\n   std::setlocale(LC_ALL, "C.UTF-8");\n   wcout.imbue(locale("C.UTF-8"));\n\n    wstring s;\n    wcin >> s;\n    wcout << s.length() << " " << (s == L"\xc3\xa1\xc3\xa9\xc3\xba");\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用ideone测试了两者,工作正常。我没有 clang++/libc++,所以无法测试此行为,抱歉。

\n