I want to know how to check if my input buffer(perhaps its called stdin) is empty or not. i dont want the program to stop if the buffer is empty, and i dont want the input to necessarily end with '\n', therefore just using scanf is not enough.
i tried searching on google and on this website but no answer was enough. i tried using feof(stdin) like this:
int main()
{
char c,x;
int num;
scanf("%c",&c);
scanf("%c",&x);
num=feof(stdin);
printf("%d",num);
}
but all it did was printing 0 no matter the input. adding fflush(stdin) after the second scanf gave the same result. other answers suggested using select and poll but i couldnt find any explanations for those functions. some other forum told me to use getchar() but i think they misunderstood my question.
on the google search i tried: C how to check input buffer empty, C stdin empty, c "input buffer" check empty. this is a general question, its not for a specific code so it doesnt matter why i need it.
**if you suggest i use select/poll, could you please add an explanation about how to use those?
You can use
select()
to handle the blocking issue and the man page select(2) has a decent example that pollsstdin
. That still doesn't address the problem of needing a line-delimiter ('\n'
). This is actually due to the way the terminal handles input.On Linux you can use termios,
Try this,
ungetc(ch, stdin);
is added to eliminate the side effect.Here is the code for solving this:
fseek
will put the pointer at the end of thestdin
input buffer.ftell
will return the size of file.If you don't want to block on an empty stdin you should be able to fcntl it to O_NONBLOCK and treat it like any other non-blocking I/O. At that point a call to something like fgetc should return immediately, either with a value or EAGAIN if the stream is empty.