将 std::u16string 写入文件?

问题描述 投票:0回答:2

我正在尝试将 std::u16string 写入文件
使用 std::string 可以轻松完成此操作

// ... pseudocode
std::wofstream outfile;
outfile.open("words.txt", std::ios_base::app);
outfile << "something"; 
outfile.close();
// ...

但是如何将 std::u16string 写入文件?

谢谢

c++ string c++11 wstring
2个回答
2
投票

您需要创建一个

basic_ofstream
,其char类型相当于
u16string
值类型,应该是
char16_t
:

typedef std::basic_ofstream<char16_t> u16ofstream;

u16ofstream outfile("words.txt", std::ios_base::app);
outfile << someu16string; 
outfile.close();

或者,您可以将

u16string
转换为常规
string
,然后将其写入普通
ofstream
,但您必须自行处理转换并处理字符串的编码。

wofstream
也可能与某些平台(特别是 Windows)上的
u16string
兼容,但它不可移植。


0
投票

使用 std::ofstream::write():

outfile.write(reinterpret_cast<const char*>(some_u16str), some_u16_str.length() * sizeof(char16_t));

我听说不建议使用reinterpret_cast,所以它可能在某些平台上不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.