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("Press Any Key to Continue\n"); //The Void Function Here //Then I will call the function that will start the game
I'm compiling with Visual Studio 2012.
Method 1. If you just detect enter key pressed at any time, use getchar() or cin. get() function. printf("Enter key is pressed"); Sleep(1000); //wait for check printed message.
“c++ press any key to continue” Code Answer'scin. get() //(expected for Enter, need #include <iostream>).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With