Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Terminating the program by pressing a key

Tags:

c

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 ?

like image 300
Andreas Grech Avatar asked Oct 26 '09 12:10

Andreas Grech


People also ask

How do you terminate a program in C?

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.

Which key is used to terminate the program?

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.

What is exit () function in C?

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.

What does exit 0 do in C?

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.


2 Answers

getc(stdin); is portable in this sense

like image 185
alexkr Avatar answered Oct 13 '22 16:10

alexkr


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;
}
like image 44
John Bode Avatar answered Oct 13 '22 14:10

John Bode