使用C ++管理中文.txt

时间:2018-10-16 17:48:39

标签: c++ utf-8

我正在尝试在控制台中显示电影文本,它是从Wikipedia中粘贴到.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;
    }

我收到: 错误:与'operator <<'不匹配(操作数类型为'std :: ostream {aka std :: basic_ostream}'和'std :: __ cxx11 :: wstring {aka std :: __ cxx11 :: basic_string}' )|

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

1 个答案:

答案 0 :(得分:0)

有两个错误:

否则不匹配

        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字符意味着文件已被读取,因此将使注入失败。因此,始终在打开文件之前先对其进行加密。