c语言中非,C语言中非堵塞的获取 keyboard value

getchar,scanf,getch,这些,如果用户没有输入就会阻塞

Windows用_kbhit()(因为是立即返回的,你可能要放到循环里),判断是不是有键按下,然后用_getch()取走

/* Standard C libraries */

#include

#include

#include

/* OS specific libraries */

#ifdef _WIN32

/* _WIN32: Sleep in */

#include

#endif

#ifdef __linux__

#include

#include

/* __linux__: usleep in */

#include

void Sleep(int micro_seconds)

{

usleep(micro_seconds * 1000);

}

#endif

int main(void)

{

printf("Hello!\n");

char ch;

while (ch != 'q')

{

#ifdef _WIN32

if (kbhit())

ch = getch();

#endif

Sleep(500);

system("cls");

printf("Enter [q] key to exit\n");

}

printf("Welcome back!\n");

system("pause");

return 0;

}

Linux可以用 fcntl

#include

#include

#include

#include

#include

#include

int fd=-1,ret=-1;

char buf[200]={0};

int flag=-1;

//将键盘设置为非阻塞

flag=fcntl(0,F_GETFL); //获取当前flag

flag |=O_NONBLOCK; //设置新falg

fcntl(0,F_SETFL,flag); //更新flag

while(1)

{

//读键盘

memset(buf,0,sizeof(buf));

ret=read(0,buf,sizeof(buf));

if(ret>0)

{

printf("键盘读取为:[%s].\n",buf);

}

}

return 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值