I want to be able to do something along the lines of Press any key to exit
at program completion, but have no been able to figure out how to.
When I run
Depending on your need and platform, you may use getch() (or _getch()), or ultimately getchar().
The problem with getchar()
is that it requires the user to press "enter".
The advantage with getchar() is that it is standard and cross-platform.
getch()
get all the other property : it just needs a key to be pressed, no display, no "enter" needed. But it's non standard, so support varies depending on platform.
Alternatively, for windows only, there is also :
system("pause");
getchar()
is the right way to go, but you'll run into problems caused by scanf
leaving '\n'
in the input buffer - it will return immediately. See Why doesn't getchar() wait for me to press enter after scanf()?
To do this quick hack, the most common two options are:
/* Windows only */
#include <stdlib.h>
system("pause");
and
/* Cross platform */
#include <stdio.h>
printf("Press enter to continue...\n");
getchar();
I suggest the latter method, though the first method really triggers on "any" key while the bottom one only triggers on enter.
Use getchar()
:
...program...
printf("press enter to continue...\n");
getchar()
Possible options: 1) system("pause"); 2) getch(); 3) getchar();
It's an old question but thought I'd add a technique I use when testing programs on a Windows box.
Compile program into an exe. And then create a batch script to "wrap" the program along the lines of:
@echo off
foo.exe
pause
exit
which will execute your program as it should be, without any dirty hacks, while allowing you to pause the window and see the output.