在C++管理一家中国.txt

Manage a Chinese .txt in C++

本文关键字:中国 txt 一家 管理 C++      更新时间:2023-10-16

我正在尝试在控制台中显示一个 cinese 文本,它已从维基百科粘贴到.txt文件中(我不知道编码,也许是 UTF-8?

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;

int main () {
const locale utf8_locale
= locale(locale(), new std::codecvt_utf8<wchar_t>());
std::wifstream file("dao.txt");
file.imbue(utf8_locale);
wstring s;
if (file.is_open())
{
while (getline(file, s))
{
cout << s << 'n';
// Do something with the string
}
else cout << "Unable to open file";
myfile.close();
}
return 0;
}

我收到:错误:与"运算符<<"不匹配(操作数类型为"std::ostream {aka std::basic_ostream}"和"std::__cxx11::wstring {aka std::__cxx11:::basic_string}"(|

为什么<<</em>没有过载?

有几个错误:

否则不匹配,如果

if (file.is_open())
{
...
else cout << "Unable to open file";
...
}

使用 std::wcout。s是一个宽字符串。使用宽输出。

std::wcout << s << 'n';  // not std::cout notice the w 

没有变量叫myfile我的意思可能是file

/*my*/file.close();

注意:

在打开溪流之前,您必须灌输它。

std::wifstream file;
file.imbue(utf8_locale);
file.open("dao.txt");

问题是,如果从文件中读取了任何字符,则灌输将失败。一些实现会检查是否有 BOM 标记(如果没有,则放回字符(。但是检查这些 BOM 字符意味着文件已被读取,因此会使输入失败。因此,在打开之前始终灌注文件。