How to Simulate "Press Any Key to Continue"

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:


  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>, Windows only).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

Press Any Key to Continue function in C

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.

How to implement Press Any Key To Exit

You can use the ncurses library to do this. The downside to this solution is that you won't be able to use cout for outputting anymore.

#include <ncurses.h>
int main()
{
initscr();
printw("Press Any Key To Exit...");
getch();
endwin();
}

Be sure to -lncurses when compiling

Press any key to continue from another script

You can pipe the input to one.sh from two.sh. See an example below.

one.sh

echo "Running one.sh...";
echo "Enter your name: ";
read name;
echo "Hello $name..!!";
echo "End one.sh";

two.sh

echo "Running two.sh...";
name=World
echo $name | ./one.sh;
echo "End two.sh";

However, if your application (two.sh) needs to make several interactions with another command line application (one.sh), then you can use expect.

How can I surpass Press any key to continue ... in python?

Using the subprocess module is always suited and superior to os.system.

Just do

sp = subprocess.Popen("testfile.bat", stdin=subprocess.PIPE)
sp.stdin.write("\r\n") # send the CR/LF for pause
sp.stdin.close() # close so that it will proceed

and you should be done.



Related Topics



Leave a reply



Submit