C中的“按任意键继续”function

如何在C编程中创建一个可以作为“按任意键继续”的void函数?

我想做的是:

printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); //The Void Function Here //Then I will call the function that will start the game 

使用C标准库函数getchar() ,getch()是boreland函数而非标准函数。

仅用于Windows TURBO C.

 printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); getchar(); 

你应该按回车键。 为此,printf语句应按ENTER键继续。

如果按a,则需要再按ENTER键。
如果按ENTER键,它将继续正常。

因此,它应该是

 printf("Let the Battle Begin!\n"); printf("Press ENTER key to Continue\n"); getchar(); 

如果您使用的是Windows,那么可以使用getch()

 printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); getch(); //if you press any character it will continue , //but this is not a standard c function. 

 char ch; printf("Let the Battle Begin!\n"); printf("Press ENTER key to Continue\n"); //here also if you press any other key will wait till pressing ENTER scanf("%c",&ch); //works as getchar() but here extra variable is required. 

你没有说你正在使用什么系统,但是因为你已经有了一些可能适用于Windows的答案,我会回答POSIX系统。

在POSIX中,键盘输入来自称为终端接口的东西,默认情况下缓冲输入行直到命中Return / Enter,以便正确处理退格。 您可以使用tcsetattr调用更改它:

 #include  struct termios info; tcgetattr(0, &info); /* get current terminal attirbutes; 0 is the file descriptor for stdin */ info.c_lflag &= ~ICANON; /* disable canonical mode */ info.c_cc[VMIN] = 1; /* wait until at least one keystroke available */ info.c_cc[VTIME] = 0; /* no timeout */ tcsetattr(0, TCSANOW, &info); /* set immediately */ 

现在,当您从stdin(使用getchar()或任何其他方式)读取时,它将立即返回字符,而无需等待Return / Enter。 此外,退格将不再“工作” – 而不是删除最后一个字符,您将在输入中读取实际的退格字符。

此外,您需要确保在程序退出之前恢复规范模式,或者非规范处理可能会对您的shell或任何调用您的程序的人造成奇怪的影响。

使用getch()

 printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); getch(); 

Windows替代应该是_getch() 。

如果您使用的是Windows,那么这应该是完整的示例:

 #include  #include  int main( void ) { printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); _getch(); } 

PS @ @Rörd指出,如果你在POSIX系统上,你需要确保curses库设置正确。

试试这个:-

 printf("Let the Battle Begin!\n"); printf("Press Any Key to Continue\n"); getch(); 

getch()用于从控制台获取字符,但不会回显到屏幕。