【发布时间】:2021-03-13 13:11:40
【问题描述】:
我正在开发一款主机游戏。它在更新地图后使用屏幕缓冲区刷新控制台窗口。
这是while 的主要循环。
while (true) {
//player.doStuff(_kbhit());
//map.update();
WriteConsoleOutputCharacter(
console.getScreenBuffer(),
(LPWSTR)map.getScreen(),
map.getWidth() * map.getHeight(),
{ 0, 0 }, console.getBytesWritten()
);
Sleep(1000 / 30);
}
在此循环之前,我从.txt 文件中获取地图布局:
class Map {
int width, height;
wchar_t* screen;
public:
wchar_t* getScreen() {
return screen;
}
void setScreen(std::string layoutFile, std::string levelDataFile) {
std::ifstream levelData(levelDataFile);
levelData >> width >> height;
screen = new wchar_t[(width + 1) * height];
levelData.close();
std::wifstream layout(layoutFile);
std::wstring line;
for (int j = 0; j < height; j++) {
std::getline<wchar_t>(layout, line);
for(int i = 0; i < width; i++) {
screen[j * width + i] = line.at(i);
}
screen[width * (j + 1)] = L'\n';
}
layout.close();
}
};
map.setScreen("demo.txt", "demo_data.txt");
问题是打印出来的地图显示为一个没有任何换行符的字符串,像这样:
00000__00000
当我期望它看起来像这样时:
0000
0__0
0000
我尝试在每行写入后添加L'\n'、L'\r\n',但它不起作用。
【问题讨论】:
-
一行的长度是
width+1,包括换行符。由于这个原因,索引的公式(j * width + i和width * (j + 1))是错误的。还要小心以空字符结束字符串,而不是换行符。 -
@fabian 但问题是 getline 只返回一个没有 \n 的字符串,在这种情况下,一行的长度是
width而不是width+1。因此,我尝试使地图 1 符号比线宽,并手动添加换行符,这是行不通的
标签: c++ winapi console windows-console