使用任意键(c ++)停止程序

Stopping the program with any key(c++)

本文关键字:程序 任意键      更新时间:2023-10-16

如何制作一个在按下某个键时停止程序的函数?(该函数需要作为线程运行(。我试过了,但不起作用

  _getch() == true;
  if(_getch() == true){
    exit(0);
  }

你可以使用 ncurses 库,

#include <ncurses.h>
... 
initscr();          /* Start curses mode   */
getch();            /* Wait for user input */
endwin();           /* End curses mode     */
...

您可以在NCURSES编程HOWTO中找到与之相关的文档

答案存在于askubuntu。

以下内容适用于Windows和linux/unix:

#include <iostream>
...
std::cout << "Press 'Return' to end." << std::endl;
cin.sync(); // instead of flush()
std::cin.get();

第一个std::cin.sync()清除输入 que,下一个命令 等待输入。