C: Terminating the program by pressing a key
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
?
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;
}
You could fix the terminal window to not go away.
getchar()
is standard but due to line buffering you will still need to press Enter
before getchar
returns.
I prefer running program from command line.
I think using getch() is the most common by far is keeping a console window from closing , but in C++ most experienced programmers will recommend that you use cin.get
std::cin.get();
instead of:
getch();
Are you using Turbo C compiler? getch()
is widely used there.
OTOH if you want the program to wait, run the binary inside the shell/terminal/prompt. Navigate to that directory and invoke
Windows:
C:> executable.exe
Linux:
~$ ./exec
You can use getchar()
, the only problem being that it is buffered. getch()
isnt buffered. You can make getchar()
also to be non-buffered, but the code for that is not worth it. I tried it once, but due to it's sheer complexity never bothered to try it again.
In addition to other answers, you can also use this in windows, especially if your intention is to wait for key press to finish the program:
system("pause");
Just trying to answer something different, you can use
while(1)
sleep(10);
at the end of main function (before return 0;
) and then you can press ctrl-c to terminate the program. I think you should not face portability issue and I hope this is not bad programming practice either :)
精彩评论