【问题标题】:How to read a Spanish encoded file and store it character by character?如何读取西班牙编码文件并逐字符存储?
【发布时间】:2015-08-31 06:34:46
【问题描述】:

我无法读取文件并将其存储在内存中,因为它是用西班牙语编写的,我认为这可能是编码问题。我想知道一种分别打印或存储每个字符的方法。我已经尝试了很多东西,但我发现最准确的方法是使用方法wstring readFile(const char* filename),如代码所示:

#include <sstream>
#include <fstream>
#include <iostream>
#include <fstream>
#include <algorithm>

std::wstring readFile(const char* filename)//Read using a file using wifstream
{
    std::wifstream wif(filename);

    std::wstringstream wss;

    wss << wif.rdbuf();
    return wss.str();
}

int main()
{
    std::wstring fileContent = readFile("read.txt"); //Read file to wstring.

    std::wcout << fileContent ; //Print the wstring. This works fine.
    std::cout << " " << std::endl;//Give spacing.

    wchar_t a; //create variable wchar_t.
    int fs = fileContent.size();
    std::cout << "Number of chars: " << fs; //Check content size.

    for (int i = 0; i < fs; i++){ //I want to print each letter.

        a = fileContent.at(i);  //Assign to "a" content of specified index.

        std::wcout << " " << a ; //Print character stored in variable a.
    }
}

在变量wchar_t a 中存储或打印fileContent.at(i)fileContent[i] 的值时似乎出现了问题。你知道代码中有哪些可以改进的地方或者给我一个解决这个问题的指南吗?

如果有帮助,我正在使用 Macintosh 和 Linux。 谢谢!

【问题讨论】:

  • "character by character" 在 Unicode 中永远没有意义。您应该完全避免 wchar_t 并使用 utf-8 编码的 char 容器,然后根据您是否要计算字节、代码单元、代码点、列、字素或字素簇使用单独的 API。
  • It seems there is a problem 那么,有什么问题呢?你期望什么结果,你观察到什么,两者有何不同?
  • 所以问题是控制台中的预期结果,以便查看 wchar_t a 变量中存储的字符串。例如,我希望在控制台中看到重音 i as í,但我得到了:??。
  • 查看存储在内存中的值(在 IDE 的帮助下)我只是发现只有当字符串的值试图在控制台中显示时才会出现问题,因为在内存中正在以正确的方式工作。感谢您的帮助。

标签: c++ c++11 utf-8 wchar-t wstring


【解决方案1】:

您正在使用 std::wifstream,它使用 wchar_t(UTF-16 或 UTF-32,取决于平台)返回 Unicode 字符,但您没有告诉 std::wifstream 源文件的编码是什么它可以将文件数据从西班牙语解码为 Unicode。在开始读取文件数据之前,您需要将 imbue() 一个适当的西班牙语言环境设置为 std::wifstream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2011-10-30
    • 2015-10-07
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多