无法使用ofstream将汉字写入文本文件

2024-01-10

我在用着std::wofstream在文本文件中写入字符。我的字符可以包含来自不同语言(英语到中文)的字符。 我想打印我的vector<wstring>到该文件中。 如果我的矢量仅包含英文字符,我可以毫无问题地打印它们。 但是如果我写中文字符我的文件仍然是空的。

我浏览了堆栈溢出,所有答案基本上都说使用库中的函数:

#include <codecvt>

我无法包含该库,因为我在版本 5.11 中使用 Dev-C++。 我做了:#define UNICODE在我所有的头文件中。 我想这个问题有一个非常简单的解决方案。 如果有人能帮助我,那就太好了。

My code:

#define UNICODE
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string Path = "D:\\Users\\\t\\Desktop\\korrigiert_RotCommon_zh_check_error.log";
    wofstream Out;
    wstring eng = L"hello";
    wstring chi = L"程序";

    Out.open(Path, ios::out);

    //works.
    Out << eng;

    //fails
    Out << chi;

    Out.close();

    return 0;
}

亲切的问候


即使名字是wofstream意味着它是一个宽字符流,但事实并非如此。它仍然是一个char使用区域设置中的转换面来转换的流wchars to char.

这是 cppreference 所说的:

所有文件 I/O 操作通过std::basic_fstream<CharT>使用std::codecvt<CharT, char, std::mbstate_t>流中渗透的语言环境的一个方面。

因此,您可以将全局区域设置设置为支持中文的区域设置,或者imbue溪流。在这两种情况下,您都会得到一个字节流。

#include <locale>
//...
const std::locale loc = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>);

Out.open(Path, ios::out);
Out.imbue(loc);

很遗憾std::codecvt_utf8已被弃用[2 http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0618r0.html]。这个MSDN 杂志 文章解释了如何使用进行 UTF-8 转换MultiByteToWideChar .

这里的微软/vcpkg https://github.com/Microsoft/vcpkg/commit/ca692e52cee55da2f9d65d66e5f3997f3a335743的变体to_utf8转换:

std::string to_utf8(const CWStringView w)
{
    const size_t size = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string output;
    output.resize(size - 1);
    WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, output.data(), size - 1, nullptr, nullptr);
    return output;
 }

另一方面,您可以使用普通的二进制流并编写wstring数据与write().

std::ofstream Out(Path, ios::out | ios::binary);

const uint16_t bom = 0xFEFF;
Out.write(reinterpret_cast<const char*>(&bom), sizeof(bom));    // optional Byte order mark

Out.write(reinterpret_cast<const char*>(chi.data()), chi.size() * sizeof(wchar_t));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用ofstream将汉字写入文本文件 的相关文章

随机推荐