C++ 更新控制台输出

标签 c++ console output

我正在尝试编写一个程序来打印出一个网格,并在给定的 x 和 y 坐标下更改网格中的一个值。例如,如果用户输入 X:0 和 Y:0,它会将下图中的值“9”更改为预定义值(在这种情况下,我想将值 9 更改为 0)。

enter image description here

我的问题是,是否可以更新控制台的输出,以便“0”覆盖“9”而无需再次打印出整个网格。我希望能够多次执行此操作。

如果那不可能,我怎样才能按照我实现的方式打印出更新的网格?如果我要将显示网格 for 循环 放在一个单独的函数中,我将需要调用 2d 数组作为参数,我相信你不能这样做。

这是我的:

void generateGrid(int diff){
        srand(time(NULL));
        int arr[maximum][maximum];
            for (int i=0;i<diff;i++)
        {
            for (int j=0;j<diff;j++)
            {
                arr[i][j] = rand() % 9 + 1;
            }
        }
        cout<<"\n\tPuzzle\n\t";
            for(int i=0;i<diff;i++)
            {
                cout<<i<<" ";
            }
                cout<<"\n\n";
            for(int i=0;i<diff;i++)
            {
                cout<<i<<"\t";
                for(int j=0;j<diff;j++)
                {
                    cout<<arr[i][j]<<" ";
                }
                    cout<<"\n";
            }
       int x, y;
        cout<<"\nEnter x value: ";
        cin>>x;
        cout<<"Enter y value: ";
        cin>>y;
        arr[x][y] = 0;
    }

Diff指的是拼图大小(难度)

其他地方:

int easy = 5;
int medium = 8;
int hard = 10;
int maximum = 10;

最佳答案

如果您的控制台支持 ANSI escape codes ,你可以上升多行并重新打印它们,e。 G。像这样:

printf("hello\n");
printf("\x1b[A");  // you can add the number of lines: "\x1b[7A"
printf("hola \n"); // add sufficient spaces to overwrite previous output!

这适用于大多数 linux shell,但 Windows 直到 Win10 才支持它。

关于C++ 更新控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42807553/

相关文章:

c++ - 在模板函数中使用 initializer_list

python - 在 PyDev 中打印到控制台

java - 二维数组,输出不正确

c++ - 将 std::cerr 写入 txt 文件

c++ - OpenCV 中的 BoW 使用预先计算的特征

c++ - 如何检测 << 运算符链的末尾

c++ - getter 和 setter 的错误

java - 如何检查 Java 程序的输入/输出流是否连接到终端?

java - Windows/Java 中的反向换行

c - 每个数字的输出都一样吗?