C中的“按任意键继续”功能

问题描述 投票:24回答:4

如何在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

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

c
4个回答
39
投票

使用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.      

14
投票

你没有说你正在使用什么系统,但是因为你已经有了一些可能适用于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 */

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

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


3
投票

使用getch()

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

Windows替代应该是_getch()

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

#include <conio.h>
#include <ctype.h>

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

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


1
投票

试试这个:-

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

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

© www.soinside.com 2019 - 2024. All rights reserved.