如果我在控制台中显示了一个字符网格,是否有任何实用的方法可以重写多行代码,以便在控制台的相同行上输出更改后的网格。
例如,我想要这段代码:
#include <iostream>
using namespace std;
int main() {
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
cout << "-";
}
cout << endl;
}
getchar();
for (int i=0; i<5; i++) {
cout << '\r';
for (int j=0; j<5; j++) {
cout << "x";
}
cout.flush();
}
return 0;
}
输出:
-----
-----
-----
-----
-----
然后,在用户输入时,将其覆盖;
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
我看到其他人通过输出'\ r'来重写单行来显示加载条类型显示的其他示例,但是我不确定是否有直接的方法可以完成多行?
我正在使用MinGW。
一种解决方案:
#include <iostream>
#include <stdio.h>
#include <windows.h>
using namespace std;
void gotoxy( int column, int line )
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle( STD_OUTPUT_HANDLE ),
coord
);
}
int main() {
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
cout << "-";
}
cout << endl;
}
getchar();
gotoxy(0,0);
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
cout << "x";
}
cout << endl;
}
return 0;
}
最佳答案
您可以使用SetConsoleCursorPosition
设置光标位置。