tags:

views:

40

answers:

1

This is the kbhit implementation that I found, but for some reason it just waits a key to be pressed instead of returning some result other than 0. It doesn't really function as kbhit...

int kbhit(void)
{
    struct timeval tv;
    fd_set read_fd;

    tv.tv_sec=0;
    tv.tv_usec=0;
    FD_ZERO(&read_fd);
    FD_SET(0,&read_fd);

    if(select(1, &read_fd, NULL, NULL, &tv) == -1)
        return 0;

    if(FD_ISSET(0,&read_fd))
        return 1;

    return 0;
}

Can anyone explain me what the problem is? I'm using Linux, btw.

I think you might have misunderstood me, and thought that it actully returns non zero value after a key stroke. my problem is that kbhit always WAITS for a key stroke.

A: 

stdin is probably line-buffered. You'll need to switch it to unbuffered while trying to detect a keypress.

Ignacio Vazquez-Abrams
How do I do that?
Sason
@Sason:exactly how I told you to on http://stackoverflow.com/q/3962263/371250
ninjalj
@Ignacio: technically, stdin would be on canonical mode. setvbuf() is for output streams.
ninjalj