system("cls") 执行一个 shell 命令来清除屏幕。这非常低效,而且绝对不适用于游戏编程。
不幸的是,屏幕 I/O 取决于系统。当您提到“cls”而不是“clear”时,我猜您正在使用 Windows 控制台:
编辑:
我了解您在编写控制台应用程序而不是功能齐全的 win32 图形应用程序时使用基于字符的输出。
然后您可以通过仅清除控制台的一部分来调整上面提供的代码:
void console_clear_region (int x, int y, int dx, int dy, char clearwith = ' ')
{
HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE); // get console handle
CONSOLE_SCREEN_BUFFER_INFO csbi; // screen buffer information
DWORD chars_written; // count successful output
GetConsoleScreenBufferInfo(hc, &csbi); // Get screen info & size
GetConsoleScreenBufferInfo(hc, &csbi); // Get current text display attributes
if (x + dx > csbi.dwSize.X) // verify maximum width and height
dx = csbi.dwSize.X - x; // and adjust if necessary
if (y + dy > csbi.dwSize.Y)
dy = csbi.dwSize.Y - y;
for (int j = 0; j < dy; j++) { // loop for the lines
COORD cursor = { x, y+j }; // start filling
// Fill the line part with a char (blank by default)
FillConsoleOutputCharacter(hc, TCHAR(clearwith),
dx, cursor, &chars_written);
// Change text attributes accordingly
FillConsoleOutputAttribute(hc, csbi.wAttributes,
dx, cursor, &chars_written);
}
COORD cursor = { x, y };
SetConsoleCursorPosition(hc, cursor); // set new cursor position
}
编辑 2:
此外,这里还有两个可以与标准 cout 输出混合使用的光标定位功能:
void console_gotoxy(int x, int y)
{
HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE); // get console handle
COORD cursor = { x, y };
SetConsoleCursorPosition(hc, cursor); // set new cursor position
}
void console_getxy(int& x, int& y)
{
HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE); // get console handle
CONSOLE_SCREEN_BUFFER_INFO csbi; // screen buffer information
GetConsoleScreenBufferInfo(hc, &csbi); // Get screen info & size
x = csbi.dwCursorPosition.X;
y = csbi.dwCursorPosition.Y;
}