Reputation: 347
I am attempting to let the user confirm his action by pressing the ENTER key - if any other key is pressed, the said 'action' does not occur.
However, instead of just a simple if((ch=getchar())=='\n') {...}
, I actually want to clear stdin
in case the user enters something like hello\n
instead of letting that being read the next time I take input in my program.
The function I use to clear stdin
is :
void eat()
{
int eat; while ((eat = getchar()) != '\n' && eat != EOF);
}
However, this strategy leaves me with the user having to press ENTER twice , since it ' eats ' the newline that is supposed to make it send the input to my program (in a terminal).
What can be the simplest, most elegant solution ?
NOTE : I cannot use non-portable solutions like setting the console to send each character immediately by using the POSIX terminos.h
.
Upvotes: 0
Views: 140
Reputation:
Sounds like you want to read a line and then check whether it's empty or not? Looks like a job for fgets(..., stdin)
char mystring [100];
fgets (mystring , 100 , stdin);
if (*mystring == '\n') {//confirmed}
Upvotes: 1