C中的"按任意键继续"功能

Sun*_*Kim 27 c

如何在C中创建一个可以作为"按任意键继续"的空函数?

我想做的是:

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
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2012进行编译.

Gan*_*har 40

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

仅用于Windows TURBO C.

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");  
getchar();    
Run Code Online (Sandbox Code Playgroud)

你应该按返回键这里.为此,printf语句应该按ENTER继续.

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

因此,它应该是

printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");  
getchar();    
Run Code Online (Sandbox Code Playgroud)

如果您使用的是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.
Run Code Online (Sandbox Code Playgroud)
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.      
Run Code Online (Sandbox Code Playgroud)

  • 我可以按20000键,如果它们都不是Return键(或"Any"键;-),我就无法继续.对于这种特殊情况,这不是正确的解决方案. (3认同)
  • 我明白那个.这夸张了.我的观点是必须按下Return键,这意味着无论您按下多少键,如果它们都不是Return键,则会出现问题,因为您应该能够按一个键,无论键是什么键是的,程序应该继续. (2认同)
  • 作为一个迂腐的评论,那些“printf”调用可能应该是对“puts”的调用。:-) (2认同)

Chr*_*odd 15

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

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

#include <termios.h>

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 */
Run Code Online (Sandbox Code Playgroud)

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

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