【问题标题】:Exit program if i get any char如果我得到任何字符退出程序
【发布时间】:2012-05-16 00:25:06
【问题描述】:

我正在创建一个程序,如果我按下任何键,我想退出该程序。 到目前为止,我只能在按下返回时这样做,因为 getch 需要按下返回。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
static void * breakonret(void *instance);
int main(){
  pthread_t mthread;
  pthread_create(&mthread, NULL, breakonret, NULL);
  while(1){
    printf("Data on screen\n");
    sleep(1);
  }
}
static void * breakonret(void *instance){
  getchar();
  exit(0);
}

【问题讨论】:

    标签: c++ terminal getchar


    【解决方案1】:

    (我将问题从getch 重新标记为getchar,因为它们是两个不同的东西)。

    如您所见,getchar 在返回之前等待按下返回。如果您希望它在按下任何键后立即返回,则需要使用不同的功能。在 Windows 上,有一个名为 getch() 的内置函数可以做到这一点,在 &lt;conio.h&gt; 中定义。在 POSIX 平台(例如 Linux、OS X)上,没有内置的 getch(),但您可以像这样编写自己的版本(来自 http://cboard.cprogramming.com/faq-board/27714-faq-there-getch-conio-equivalent-linux-unix.html):

    #include <termios.h>
    
    int getch( ) 
    {
      struct termios oldt,
                     newt;
      int            ch;
      tcgetattr( STDIN_FILENO, &oldt );
      newt = oldt;
      newt.c_lflag &= ~( ICANON | ECHO );
      tcsetattr( STDIN_FILENO, TCSANOW, &newt );
      ch = getchar();
      tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
      return ch;
    }
    

    【讨论】:

    • 两个 cmets:首先,您需要 #include 才能使其正常工作。其次,这应该适用于任何 POSIX 平台(包括 OS X),而不仅仅是 Linux。
    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多