【问题标题】:Manage a Chinese .txt in C++用 C++ 管理中文 .txt
【发布时间】:2018-10-16 17:48:38
【问题描述】:

我正在尝试在控制台中显示一个中文文本,它已从维基百科粘贴到一个 .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::wcout怎么样?
  • 您必须知道编码才能正确显示。
  • 您的终端期望什么编码? UTF-8?如果是这样,只需将其作为普通的std::string 读入(不需要刻面)并再次打印出来。 UTF-16?然后您可以尝试打印到(并从中读取)std::wcout?底线是您必须输出与显示终端所期望的相同的编码。

标签: c++ utf-8


【解决方案1】:

有几个错误:

否则不匹配if

        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 字符意味着文件已被读取,因此会使灌输失败。因此,请务必在打开文件之前对文件进行灌输。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多