universal input stream (stdin) clearing or cleaning
Primary tabs
Imagine that we have a very simple console menu function "mainmenu()" - something like this =
int mainmenu(void) { int ch; char* mtext = " Please specify the number of the task. \n * You can choose on number from set = {1} \n * Specify \"0\" to exit\n" ; char* errmes = " Error(!) = Main menu does not support this command.\n Make sure that your task number is from menu set of commands and try again. " ; while (getchar() != '\n'); /*here we are cleaning the input = fflush(stdin) isn't cool variant;or use while (getchar() != '\n'); - but this'll stop program*/ printf("\n%s",mtext ); ch = getchar() ; /*user choose an item*/ switch(ch) { case '0': printf("\n%s","you choise is item1 \n" ); /*menu item = just put here the name of your function instead of printf()*/ break; case '1': printf("\n%s","you choise is item2 \n" ); /*menu item = here the name of your function instead of printf()*/ break; default: printf("\n%s\n", errmes); } return 0; }
There are 2 situations of mainmenu() work =
1) We get the first when the stdin wasn't empty at the moment we call this function =
int main() { char ch; printf("\n%s","please specify a one symbol" ); /* but user've put "dgfhj3 \n" */ ch = getchar(); /*in buffer we have "gfhj3 \n"*/ mainmenu(); return 0; }
And in this situation all will we ok, because line
while (getchar() != '\n');
will remove all data from stdin.
2) But may be the second variant - when the stdin is clear (empty) =
int main() { /*in buffer we have nothing*/ mainmenu(); return 0; }
In this situation the line
while (getchar() != '\n');
will stop the program waiting from user at least an Enter pressing - but this isn't good - least because we even don't know- should we put a prompt message like this =
printf("\n%s"," technical pause - press Enter please" );
or not.
So as I think (and need) sould be a way to avoid this stopping.
- vedro-compota's blog
- Log in to post comments
- 5520 reads