【问题标题】:Using wstring and wcout doesn't get the expected output使用 wstring 和 wcout 没有得到预期的输出
【发布时间】:2017-11-06 10:11:06
【问题描述】:

我正在用 C++ 编写一个程序,它必须处理 unicode 字符。 主要问题是我使用算法来解析我的 s/wstrings char by char

std::wstring word = L"Héllo"
for (auto &e : word)
// doing something with e

但是如果我运行这个:

std::wstring word = L"Héllo"
for (auto &e : word)
    std::wcout << e << std::endl;

我得到这个输出:

H
?
l
l
o

我做错了吗?

请注意,当我使用 std::wcout &lt;&lt; word; 时,word 会正确打印。

为@Ben Voigt 编辑

这里是std::wcout << std::hex << std::setw(4) << (int)e << L" " << e << L'\n';

  48 H
  e9 �
  6c l
  6c l
  6f o

【问题讨论】:

  • 你的控制台支持 unicode 吗?
  • 观察:不处理代理对,因为未知字符只有一行输出。
  • @Ðаn 不确定那些骗子。 OP 说完整的字符串可以正确打印,而不是逐个字符打印。
  • 在源代码本身中放置带引号的非 ASCII 字符串文字是一个基本问题。不能保证您在这些引号中输入的内容就是实际显示的字符。
  • 失败的原因必须是打印单个字符时选择了不同的operator&lt;&lt;,与整个字符串相比。要找出问题所在,需要编写一个自定义的strreambuf 类来记录对xsputnoverflow 的每次调用,并查看调用顺序如何变化。要解决这个问题,直接在wcout 上调用writeput 可能就足够了,或者在使用&lt;&lt; 之前进行转换。例如我希望wcout &lt;&lt; wstring(1, e); 会得到“写一个完整的字符串”的行为。

标签: c++ unicode wchar-t wstring wchar


【解决方案1】:

要按您的意愿打印字符,请尝试以下操作:

#include <string>
#include <iostream>
#include <fcntl.h>
#include <io.h>
int _tmain(int argc, _TCHAR* argv[])
{
    std::wstring word = L"Héllo";
    _setmode(_fileno(stdout), _O_U16TEXT);
    for (auto &e : word)
        std::wcout << e << std::endl;
    return 0;
}

更详细的说明在本帖:Why are certain Unicode characters causing std::wcout to fail in a console app?

【讨论】:

  • 这些函数不存在on Linux 是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 2017-01-30
  • 1970-01-01
相关资源
最近更新 更多