C语言 如何清除C中的屏幕?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18154579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I clear the screen in C?
提问by user2651382
I want to clear all the text that is on the screen. I have tried using:
我想清除屏幕上的所有文本。我试过使用:
#include <stdlib.h>
sys(clr);
Thanks in advance! I'm using OS X 10.6.8. Sorry for the confusion!
提前致谢!我使用的是 OS X 10.6.8。对困惑感到抱歉!
回答by Jiminion
You need to check out curses.h. It is a terminal (cursor) handling library, which makes all supported text screens behave in a similar manner.
你需要检查curses.h。它是一个终端(光标)处理库,它使所有支持的文本屏幕都以类似的方式运行。
There are three released versions, the third (ncurses) is the one you want, as it is the newest, and is ported to the most platforms. The official website is here,and there are afew goodtutorials.
有三个已发布版本,第三个 ( ncurses) 是您想要的版本,因为它是最新的,并且已移植到大多数平台。的官方网站是在这里,而且也有一些很好的教程。
#include <curses.h>
int main(void)
{
initscr();
clear();
refresh();
endwin();
}
回答by Commander Worf
The best way to clear the screen is to call the shell via system(const char *command)in stdlib.h:
清除屏幕的最佳方法是通过system(const char *command)stdlib.h调用 shell :
system("clear"); //*nix
or
或者
system("cls"); //windows
Then again, it's always a good idea to minimize your reliance on functions that call the system/environment, as they can cause all kinds of undefined behavior.
再说一次,尽量减少对调用系统/环境的函数的依赖总是一个好主意,因为它们会导致各种未定义的行为。
回答by JSQuareD
Windows:
视窗:
system("cls"); // missing 's' has been replaced
Unix:
Unix:
system("clear");
You can wrap this in a single, more portable piece of code like so:
您可以将其包装在一个更便携的代码中,如下所示:
void clearscr(void)
{
#ifdef _WIN32
system("cls");
#elif defined(unix) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
system("clear");
//add some other OSes here if needed
#else
#error "OS not supported."
//you can also throw an exception indicating the function can't be used
#endif
}
Note the check for unix is pretty expansive. This should also detect OS X, which is what you're using.
请注意,对 unix 的检查非常广泛。这也应该检测到您正在使用的 OS X。
回答by David Elliman
The availability of this function or similar ones like clrscn() are very system dependent and not portable.
此函数或类似 clrscn() 函数的可用性非常依赖于系统且不可移植。
You could keep it really simple and roll you own:
你可以保持它非常简单并滚动你自己的:
#include <stdio.h>
void clearscr ( void )
{
for ( int i = 0; i < 50; i++ ) // 50 is arbitrary
printf("\n");
}

