Simulating “Press Any Key To Exit” is easy in windows platform. We can use getch() function to simulate it. see below example for Window machine.
How to implement Press Any Key To Exit in Window System
#define _CRT_NOSTDC_NO_WARNINGS #include<stdio.h> #include<conio.h> int main() { printf(“Press Any Key To exit\n”); getch(); return 0; }
using getch is has been deprecated in new c/c++ standard. Without #define _CRT_NOSTDC_NO_WARNINGS program will not compile.
How to implement Press Any Key To Exit in Linux System
As there is not alternative of getch() function is available in Unix/Linux Based platform. So let us write your own getch() function to mimic the behavior of windows platform getch() function.
#include <unistd.h> #include<stdio.h> #include <termios.h> int getch ( ) { int ch; struct termios oldt, newt; tcgetattr ( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr ( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr ( STDIN_FILENO, TCSANOW, &oldt ); return ch; } int main (void) { printf("Press Any Key to Exit\n"); getch(); return 0; }
Another Method : By changing the behavior of terminal
#include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() { printf("Press Any Key To exit\n"); char ch = 0; /* use system call to make terminal send all keystrokes directly to stdin */ system ("/bin/stty raw"); while ( 1 ) { ch = getchar(); if( ch != 0 ) break; } /* use system call to set terminal behaviour to more normal behaviour */ system ("/bin/stty cooked"); return 0; }
Ref:
http://stackoverflow.com/questions/1449324/how-to-simulate-press-any-key-to-continue
WE RECOMMEND RELATED POST
The post How to implement “Press Any Key To Exit” in c/c++ program appeared first on wikistack.