C++ 使用fstream以中文/日文编写的文本,但未正确读取文件

C++ 使用fstream以中文/日文编写的文本,但未正确读取文件,c++,C++,我正在尝试使用cin使用fstream将用户文本(普通文本)输入到txt文件中。但是文本显示为汉字,当再次阅读时,它会显示字母表中的随机字母 char entry[10000]; std::fstream file; file.open ("a1bc3.txt", std::ios::out | std::ios::in ); if (file.is_open()){ std::cin >> entry; } else { std::cout << "

我正在尝试使用
cin
使用fstream将用户文本(普通文本)输入到txt文件中。但是文本显示为汉字,当再次阅读时,它会显示字母表中的随机字母

char entry[10000];
std::fstream file;

file.open ("a1bc3.txt", std::ios::out | std::ios::in );

if (file.is_open()){
    std::cin >> entry;
}
else {
    std::cout << "Failed to open.\n" ;
}

file << entry << std::endl;

std::cout << "\n\n" ;
char output[10000] ;
file >> output;

std::cout << output << "\n\n" ;

file.close();
return 0;
char条目[10000];
std::fstream文件;
file.open(“a1bc3.txt”,std::ios::out | std::ios::in);
if(file.is_open()){
标准::cin>>条目;
}
否则{
std::cout我使用python和c#但是在读取文件时,似乎没有指定编码

std::string path = TEXT_FILE_PATH;
std::string utf8Content = readFile(path);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> utfconv;
std::wstring utf16LeContent = utfconv.from_bytes(utf8Content);
std::string path=TEXT\u FILE\u path;
std::string utf8Content=readFile(路径);
std::wstring_转换utfconv;
std::wstring utf16LeContent=utfconv.from_字节(utf8Content);

因此,在您的情况下,将其保存在一个变量中并进行转换

您正在打印未初始化内存的内容,因为您实际上没有向
输出
数组中读取任何内容

std::fstream
只有一个读写位置。当您写入文件时,该读写位置直接位于您刚写入的数据之后。当您稍后尝试从
文件
读取时,您将一无所获,因为您读取的位置位于您写入的数据之后。因为没有什么可读取的内容,没有数据写入
输出
,最终打印未初始化内存的内容


要使其工作,您需要在写入文件后返回到文件的开头。只需调用
file.seekg(0)
文件>输出之间的某个地方

可能编码不匹配。请尝试将文本文件保存为系统默认编码。同时检查stdout终端是否可以打印汉字。@ikh我刚刚用Unicode(UTF-8)在word中打开了它,谢谢。它加载了“Hello”,但我仍然不知道如何让它读取“Hello”在终端中。与问题无关,但您确定字符数组吗?为什么不使用std::string?