conio.h https://en.wikipedia.org/wiki/Conio.h死了!
一些背景:conio.h
定义了一个 API,该 API 曾被创建用于控制 IBM PC 的(文本!)屏幕。它最初只是 MS-DOS 函数的包装器,因此您不必编写自己的程序集来创建int 21h
打电话给他们。确切的APIconio.h
从未标准化,并且因实施而异。
我假设您使用的是针对 Windows 的编译器,这些编译器通常仍提供一些变体conio.h
。但正如您所看到的,无法保证什么是真正可用的并且可以按您的预期工作。
如今,你甚至不得不问什么是屏幕?您的内容控制台窗口?但是,如果您的控制终端是例如,该怎么办?远程 shell(telnet、ssh...)?甚至不同控制台窗口实现在功能和控制方式上会有所不同。 C只知道输入和输出streams,他们将使用任何类型的终端/控制台,因为他们对screen,只是字符的输入和输出。
为了实际控制“屏幕”,Windows 提供了控制台API https://learn.microsoft.com/en-us/windows/console/console-reference,您可以直接使用它,但是您的程序仅“硬连线”到 Windows。大多数其他控制台/终端都理解某种转义码,常常是ANSI 转义码 https://en.wikipedia.org/wiki/ANSI_escape_code。从 Windows 10 开始的 Windows 也提供了对它们的可选支持。但是有各种各样的终端可以理解不同的代码(及其不同的子集),因此直接使用它们也不是一个好主意。
如今,事实上的标准用于控制终端/控制台的是诅咒API https://en.wikipedia.org/wiki/Curses_(programming_library)它起源于 BSD Unix,但存在多种系统和控制台的实现。最为显着地,ncurses https://www.gnu.org/software/ncurses/可用于many系统,甚至包括 Windows,但对于 Windows,您还可以pdcurses https://pdcurses.sourceforge.io/。甚至还有一个扩展程序 https://www.projectpluto.com/win32a.htm对于实现其的 Windowsown控制台窗口,因此您可以使用本机 Windows 控制台所没有的功能。当然,您不需要这个来只是“清除屏幕”并从键盘读取一些输入。
当你使用curses
,你必须使用所有控制台/终端输入和输出curses
函数(你不能使用stdio
功能类似于printf()
为了那个原因)。这是一个小示例程序:
#include <curses.h>
// don't include `ncurses.h` here, so this program works with
// different curses implementations
#include <ctype.h> // for `isalnum()`
int main(void)
{
initscr(); // initialize curses, this also "clears" the screen
cbreak(); // among other things, disable buffering
noecho(); // disable "echo" of characters from input
addstr("Hello, press a key!\n"); // output a constant string, like puts/fputs
refresh(); // output might be buffered, this forces copy to "screen"
int c;
do
{
c = getch(); // read a single character from keyboard
} while (!isalnum(c)); // ignore any input that's not alphanumeric
printw("You entered '%c'.\n", c); // formatted output, like printf
addstr("press key to exit.\n");
refresh();
c = getch();
endwin(); // exit curses
}
您可以编译它,例如像这样使用 gccncurses
:
gcc -std=c11 -Wall -Wextra -pedantic -ocursestest cursestest.c -lncurses
Or with pdcurses
:
gcc -std=c11 -Wall -Wextra -pedantic -ocursestest cursestest.c -lpdcurses
要了解更多信息curses
,我推荐NCURSES 编程指南 http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/.