【问题标题】:C++: How can I print unicode characters to text fileC ++:如何将unicode字符打印到文本文件
【发布时间】:2020-01-12 17:09:15
【问题描述】:

我需要将 unicode 符号打印到文件中,但我得到了它们的代码。

这是一个例子:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
    int code = 33;
    wchar_t sym = wchar_t(code);

    ofstream output ("output.txt");
    output << sym << "\n";
    output.close();

    return 0;
}

所以我希望在我的文件中看到!,但我看到的是33。我该如何解决?

【问题讨论】:

  • 你不应该使用 wofstream 吗? cplusplus.com/reference/fstream/wofstream
  • 是的,请改用std::wofstream。仅供参考,cplusplus.com 通常被认为是一个糟糕的 C++ 参考站点,您应该使用 cppreference.com (wofstream)
  • 你想要 UTF-8 还是 UTF-16?你想BOM在文件的开头吗?您的查看器是否以正确的格式打开文件?

标签: c++ string file unicode


【解决方案1】:

如何将 unicode 字符打印到文本文件中

我期待看到!在我的文件中

这是一个写作示例

UTF-8:

std::ofstream output("output.txt");
output << u8"!\n";

UTF-16:

std::basic_ofstream<char16_t> output ("output.txt");
output << u"!\n";

UTF-32:

std::basic_ofstream<char32_t> output ("output.txt");
output << U"!\n";

wchar_t 也可以工作,但仅当宽编译字符编码为 un​​icode 时。是 UTF-16 还是 UTF-32 还是其他取决于系统:

std::wofstream output ("output.txt");
output << L"!\n";

【讨论】:

    【解决方案2】:

    std::ofstreamchar 数据进行操作,并且没有任何将wchar_t 数据作为输入的operator&lt;&lt;。它确实有带有intoperator&lt;&lt;,并且wchar_t 可以隐式转换为int。这就是您将字符输出为数字的原因。

    您需要使用std::wofstream 代替wchar_t 数据。

    【讨论】:

    • @igor_bal wchar_t 数据的编码方式取决于 imbue() 进入流的语言环境
    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 2014-08-23
    • 2011-07-10
    • 1970-01-01
    • 2013-09-25
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多