将 Unicode 字符存储在.txt文件中的新行中

store unicode characters in a .txt file in new line

本文关键字:文件 新行中 txt Unicode 字符 存储      更新时间:2023-10-16

如何使用C++将文本文件中的 Unicode 字符存储在单独的行中?我尝试使用nr;还有他们的hex价值观。但是,在.txt文件中,nr被读取为垃圾值。

以下是代码片段:

{
    std::wofstream wof;
    wof.imbue(std::locale(std::locale::empty(), new std::codecvt_utf16<wchar_t, 
    0x10ffff, std::generate_header>));
    wof.open(L"file3.txt");
    wof << L"Test.x263a x263c x263d x263e A:B:C, 我一个人来  人人都爱喝可乐。 " << endl;
    wof << L"n  Another test. x002c x263a 263e" << endl;
    wof << L"n  我一个人来。      一个人     我一个人来  人人都爱喝可乐。" << endl;
    wof << L" Test x263a x263c x263d x263e 我一个人来  人人都爱喝可乐。 " << endl;
    wof << L"n 我一个人来  人人都爱喝可乐。" << endl;
}
如图

所示以二进制形式打开文件,并添加 BOM 标记L"xFEFF"以指示文件为 UTF-16 (LE( 模式。使用此方法,您需要pubsetbuf

使用L"rn"作为行尾

std::wofstream wof(L"file3.txt", std::ios::binary);
if(wof)
{
    wchar_t buf[128];
    wof.rdbuf()->pubsetbuf(buf, 128);
    wof << L"xFEFF";
    wof << L"Test.x263a x263c x263d x263e A:B:C, 我一个人来  人人都爱喝可乐。rn";
    wof << L"Another test. x002c x263a 263ern";
}