How do I create a void function that will work as \"Press Any Key to Continue\" in C?
What I want to do is:
printf(\"Let the Battle Begin!\\n\");
printf(
You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.
In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:
#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 */
Now when you read from stdin (with getchar()
, or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.
Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.
Use getch()
:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
Windows alternative should be _getch().
If you're using Windows, this should be the full example:
#include <conio.h>
#include <ctype.h>
int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.
You can try more system indeppended method: system("pause");
Try this:-
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
getch()
is used to get a character from console but does not echo to the screen.
Use the C Standard Library function getchar()
instead as getch()
is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getchar();
Here, getchar()
expects you to press the return key so the printf
statement should be press ENTER to continue
. Even if you press another key, you still need to press ENTER:
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
getchar();
If you are using Windows then you can use 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.