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;