在下面的代码中,如果用户输入1或2,则所有内容均顺利进行。消除继续循环所需的<ENTER>
但是,如果我输入除1或2之外的其他值,循环将运行,但需要额外的才能继续循环。
我该如何消除对此的需求?
#include <stdio.h>
#include <ctype.h>
#include <math.h>
void clearKeyboardBuffer() {
int ch;
while ((ch = getchar() != '\n') && (ch != EOF));
}
void entry1(){
char chArr[BUFSIZ];
char choice, ch;
int choiceint, rating;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
// converts scanned char to int
choiceint = choice - '0';
if(!isdigit(choice) || choiceint > 3){
printf("You did not enter an accepted digit.\n");
}
else if(choiceint != 3){
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
}// end of switch
}// end of else if
else{
}// end of else
clearKeyboardBuffer();
}// end of do
while(choiceint !=3);
}
可能重复[输入C后没有换行符](http://stackoverflow.com/questions/2710103/no-newline-after-input-in-c) – unwind