HI
I’m writing a program that acts as a server and has the ability to interact with the user via the terminal. if i read from the stdin i want up to 140 chars.
if the user enters more than 140 i would like to take only the first 140 chars and ignore the rest.
i try something like the following code:
struct timeval timeout;
fd_set readings;
char buf[140];
while (1) {
timeout.tv_sec = 15;
timeout.tv_usec = 0;
FD_ZERO(&readings);
FD_SET(STDIN_FILENO,&readings);
int rv = select(STDIN_FILENO+1,&readings,NULL,NULL,&timeout);
if (rv<0) {
cout << "ERROR select\n";
exit(1);
}
if (rv==0) {
cout << "Still Waiting...\n";
}
else {
cout << "A key was pressed\n";
if (FD_ISSET(STDIN_FILENO,&readings)) {
int num = read(STDIN_FILENO,&buf,140);
buf[num]='\0';
cout << buf << endl;
}
}
}
the problem is – when i enter more than 140 chars, the first 140 chars are printed, but then read() reads the rest of the data in the next iteration and prints it .
how do i clear the stdin so that the rest of the data will be ignored in the next iteration?
thank you!!
Pretty much the only choice is to read the characters and discard them until end-of-line is reached.