在C++中接受用户输入后如何清除屏幕



我尝试过使用:

  1. cout<lt"033[2j\033[01;1H";我不明白它对终端做了什么。输出:在终端上

  2. cout<lt;字符串(22,'\n'(这个解决方案占用了下面22行的光标,这是我不想要的。

  3. 系统('cs'(我为它包含了stdlib.h,但仍然出现了相同的错误,无法解决。输出:在终端上

这些是我能找到的解决方案,但没有帮助。

这是我正在尝试的代码:

#include <iostream>
using namespace std;
void rev_array(int arr[], int start, int end)
{
while(start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void print_array(int arr[], int size)
{
for(int i=0; i < size; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int main()
{
int n;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
cin>>arr[i];
cout<<"033[2j33[01;1H";

print_array(arr, n);
rev_array(arr, 0, n-1);
cout<<"Reversed array is "<<endl;
print_array(arr, n);
return 0;
}

此行:

cout<<"033[2j33[01;1H";

缺少一个前导,用于指示字符串开头的八进制转义。当我纠正这一点时,它只会将光标定位到Linux终端的顶部,而不会清除它

我不是ANSI转义序列的专家,但在互联网上快速搜索就会发现,这是用ANSI转义序列清除屏幕的方法。

cout << "33[2J33[;H";

这在Linux上对我有效。它可能也适用于MacOS和其他Unix变体。但它不会在Windows上开箱即用。要在Windows 10上启用ANSI模式,请将下面的代码适当地粘贴到程序中,然后从main调用EnableAnsi

#include <windows.h>
void EnableAnsi()
{
DWORD dwMode = 0;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(hOut, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
}

system((函数调用作为参数给定的命令。

要在基于windows的系统上清除屏幕,您可以调用(请在cls命令周围使用双引号(:

system("cls");

在基于Unix的系统使用上;清除";命令:

system("clear");

最新更新