gpt4 book ai didi

c++ - 将 unicode 字符/字符串写入文件

转载 作者:行者123 更新时间:2023-11-27 23:40:16 31 4
gpt4 key购买 nike

我正在尝试使用 std::wofstream 将 unicode 字符写入文件,但 putwrite 函数不写入任何字符字符。

示例代码:

#include <fstream>
#include <iostream>

int main()
{
std::wofstream file;
file.open("output.txt", std::ios::app);
if (file.is_open())
{
wchar_t test = L'й';
const wchar_t* str = L"фывдлао";
file.put(test);
file.write(str, sizeof(str));
file.close();
}
else
{
std::wcerr << L"Failed to open file" << std::endl;
}

std::cin.get();
return 0;
}

output.txt 文件为空,执行代码后没有写入wchar/string,为什么?我做错了什么?

编辑:纠正代码:

#include <fstream>
#include <iostream>

int main()
{
std::wofstream file;
file.open("output.txt", std::ios::app);
if (file.is_open())
{
wchar_t test = L'й';
const wchar_t* str = L"фывдлао";
file.put(test);
if (!file.good())
{
std::wcerr << L"Failed to write" << std::endl;
}
file.write(str, 8);
file.close();
}
else
{
std::wcerr << L"Failed to open file" << std::endl;
}

std::cin.get();
return 0;
}

应用代码更正后,我看到了Failed to write,但我仍然不明白我需要做什么才能编写宽字符串和字符?

最佳答案

我是这样实现的,不需要外部字符串库,比如QString!

仅使用 std 库和 c++11

#include <iostream>
#include <locale>
#include <codecvt>
#include <fstream>
#include <Windows.h>

int main()
{
std::wofstream file;
// locale object is responsible of deleting codecvt facet!
std::locale loc(std::locale(), new std::codecvt_utf16<wchar_t> converter);

file.imbue(loc);
file.open("output.txt"); // open file as UTF16!

if (file.is_open())
{
wchar_t BOM = static_cast<wchar_t>(0xFEFF);
wchar_t test_char = L'й';
const wchar_t* test_str = L"фывдлао";

file.put(BOM);
file.put(test_char);
file.write(test_str, lstrlen(test_str));

if (!file.good())
{
std::wcerr << TEXT("Failed to write") << std::endl;
}

file.close();
}
else
{
std::wcerr << TEXT("Failed to open file") << std::endl;
}

std::wcout << TEXT("Done!") << std::endl;

std::cin.get();
return 0;
}

文件输出:

йфывдлао

关于c++ - 将 unicode 字符/字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667860/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com