将 unicode 字符存储在新行的 .txt 文件中
store unicode characters in a .txt file in new line
如何使用 C++ 在单独的行中将 Unicode 字符存储在文本文件中?我尝试使用 \n
和 \r
;还有他们的 hex
值。但是,在 .txt
文件中 \n
和 \r
被读取为垃圾值。
这是代码片段:
{
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 3e" << 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"\r\n"
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, 我一个人来 人人都爱喝可乐。\r\n";
wof << L"Another test. \x002c \x263a 3e\r\n";
}
如何使用 C++ 在单独的行中将 Unicode 字符存储在文本文件中?我尝试使用 \n
和 \r
;还有他们的 hex
值。但是,在 .txt
文件中 \n
和 \r
被读取为垃圾值。
这是代码片段:
{
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 3e" << 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"\r\n"
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, 我一个人来 人人都爱喝可乐。\r\n";
wof << L"Another test. \x002c \x263a 3e\r\n";
}