【发布时间】: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