I read several same question and the answer does not satisfy me.
They think the best answer is:
while((ch = getchar()) != '\n') && ch != EOF);
There is a problem if I want to drain stdin before I asking for answer, like:
#define DRAIN() while((ch = getchar()) != '\n') && ch != EOF)
int fun() {
...
DRAIN(); //aaa, wipe other's ass before me
ch = getchar();//bbb, ask my answer
DRAIN(); //ccc, wipe myown ass
...
}
The purpose of 'aaa' is to drain characters in stdin left by previous code, maybe before entering fun() by other unknow code.
But, if at 'aaa', there is no characters in stdin, 'aaa' will block there.
So what's the best choice?
=================
I tried below, no effect.
#define DRAIN() do { \
char ch___ = 0; \
fd_set fds___; \
struct timeval tv___; \
int ret___ = 0; \
FD_ZERO(&fds___); \
FD_SET(STDIN_FILENO, &fds___); \
tv___.tv_sec = 0; \
tv___.tv_usec = 5000; \
ret___ = select(STDIN_FILENO + 1, &fds___, NULL, NULL, &tv___);\
printf("ret:%d\n", ret___); \
if (ret___ > 0) { \
while(getchar()); \
} \
}while(0)
int main()
{
printf("#");
fflush(stdout);
getchar();
DRAIN();
printf(">");
fflush(stdout);
printf(":%c\n", getchar());
DRAIN();
return 0;
}
$ ./a.out
#123
ret:0
>:2
ret:0
====2nd edit====
Seem this works, I am in Linux env:
#define DRAIN() do { \
int flg___ = 0; \
int flg___bak = 0; \
char ch___ = 0; \
flg___ = fcntl(STDIN_FILENO, F_GETFL, 0); \
flg___bak = flg___; \
flg___ |= O_NONBLOCK; \
fcntl(STDIN_FILENO, F_SETFL, flg___); \
while((ch___ = getchar()) != '\n' && ch___ != EOF); \
fcntl(STDIN_FILENO, F_SETFL, flg___bak); \
}while(0)