I\'m just wondering whether is it possible and how do I implement this feature, where we exit from the loop if there\'s no input from the user. For example, I want to exit t
Use select()
function to set a timeout for your scanf
The following code is an example of how use it.
#include
#include
#include
int main(void)
{
int x;
fd_set set;
struct timeval timeout = {0};
FD_ZERO(&set);
while(1)
{
timeout.tv_sec = 30;
FD_SET(fileno( stdin ), &set);
printf ("enter a number:");
fflush (stdout);
if (select(FD_SETSIZE, &set, NULL, NULL, &timeout))
{
scanf("%d", &x);
printf("The number you put is %d\r\n",x);
}
else
{
printf("\r\nTimeout: Stop reading\r\n");
break;
}
}
}