简体   繁体   中英

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;
}

您可以修复终端窗口不要消失。

getchar()是标准的,但是由于行缓冲,你仍然需要在getchar返回之前按Enter

我更喜欢从命令行运行程序。

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.

除了其他答案,您还可以在Windows中使用它,特别是如果您打算等待按键完成程序:

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM