gpt4 book ai didi

c++ - 如果我得到任何字符就退出程序

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:48 24 4
gpt4 key购买 nike

我正在创建一个程序,如果我按下任何键,我想退出该程序。到目前为止,我只能在按下回车键时这样做,因为 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);
}

最佳答案

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

如您所见,getchar在返回之前等待按下返回。如果您希望它在按下任何键后立即返回,则需要使用不同的功能。在 Windows 上,有一个名为 getch() 的内置函数这是做什么的,在 <conio.h> 中定义.在 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;
}

关于c++ - 如果我得到任何字符就退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10610555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com