【发布时间】:2021-03-14 00:22:16
【问题描述】:
我正在开发一个控制台游戏,它使用 ASCII 符号作为像素。此游戏的地图存储在.txt 文件中:
████████████████
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
█ █
████████████████
为了显示地图,我从文件demo.txt逐行读取它并将每个字符写入CHAR_INFO *screen:
void setScreen(const char* layoutFile, const char* levelDataFile) {
std::ifstream levelData(levelDataFile);
levelData >> width >> height;
field = {0, 0, (SHORT)width, (SHORT)height};
screen = new CHAR_INFO[width * height];
levelData.close();
std::ifstream layout(layoutFile); //reading from a file `demo.txt`
std::string line;
for (int j = 0; j < height; j++) {
getline(layout, line);
for(int i = 0; i < width; i++) {
screen[j * width + i].Char.AsciiChar = line[i]; //writing each character of a line to screen
screen[j * width + i].Attributes = BACKGROUND_GREEN;
}
}
layout.close();
}
之后,我使用以下函数显示地图(map.getScreen() 返回指向屏幕数组的指针):
WriteConsoleOutputA(
console.getHOut(),
map.getScreen(),
{ (SHORT)map.getWidth(), (SHORT)map.getHeight() },
{ 0,0 },
&map.getField()
);
但问题是█显示为�,输出如下:
����������������
���
���
���
���
���
���
���
���
���
���
���
���
���
���
����������������
我尝试过的一些事情:
SetConsoleOutputCP(CP_UTF8); SetConsoleCP(CP_UTF8);SetConsoleCutputCP(1251);setlocale(LC_ALL, "");std::locale::global(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
【问题讨论】:
-
文件是如何编码的?您是否尝试过使用
std::wfstream而不是std::fstream? -
@alterigel 是的,我尝试使用
std::wifstream,结果是一样的。文件编码在UTF-8 -
@JaMiT,我也试过
SetConsoleCutputCP(437),但没有任何改变
标签: c++ character-encoding console