In C, I normally use the getch()
function to wait for a key to be pressed and then end the program, but recently I read that since it's not a standard function, it's bad programming practice to use it.
So instead of the following:
int main() {
dosomething();
getch(); //wait for the user to see the results and press a key to end
return 0;
}
What should I do to replace the getch
?
Unlike the return statement, it will cause a program to stop execution even in a function. And the exit() function can also return a value when executed, like the return statement. So the C family has three ways to end the program: exit(), return, and final closing brace.
To quickly force quit on Windows , use the keyboard shortcut Alt + F4. Make sure the app or program window is open when you click Alt + F4.
The exit() function in C. The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.
exit is a jump statement in C/C++ language which takes an integer (zero or non zero) to represent different exit status. Exit Success: Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt.
getc(stdin);
is portable in this sense
Using a non-standard I/O function isn't bad practice per se; it becomes an issue if you intend to port this code to a different platform that doesn't support getch()
.
The problem is, there are no standard library functions that detect individual keystrokes (getchar()
and fgetc()
are buffered and require you to hit Enter before they return); you're going to have to use something non-standard to do that. If you only intend for this code to run on this specific platform, use getch()
if that's what you need and just remember that this solution won't necessarily apply to other platforms. If you intend to port this code to platforms that don't support getch()
, isolate the system-specific call behind a wrapper function so that when you port the code, only the code inside the wrapper function needs to change.
int getKeystroke(void)
{
/**
* Put platform-specific call here
*/
return getch();
}
int main(void)
{
... // do stuff here
getKeystroke();
return 0;
}
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