-3

My code is as follow:

int main(int argc, char **argv)
{

int quit=1;
int operation;
paintUI();
init();
while(quit)
{
    printf("please input a operation code:");
    scanf("%d",&operation);
    switch(operation)
    {
        case 1:addBook();break;
        case 2:deleteBook();break;
        case 3:borrowBook();break;
        case 4:backBook();break;
        case 5:printAll();break;
        case 6:printAllBorrowed();break;
        case 7:findByNameAdapter();break;
        case 8:findByNumberAdapter();break;
        case 9:save();quit=0;break;
        case 0:system("cls");paintUI();break;
        default:printf("input error\n");break;
    }
}
return 0;
}

when I input a integer to the "operation",the code works well.But when I input a char value on purpose,the code will be caught in endless loop and print "input error" all the time.When I debug,I find that after I input a char value on purpose the statement,"scanf("%d",&operation)" ,doesn't be executed any more,so the operation code is always wrong.Somebody tell me to add a statement,"fflush(stdin);",to clear the input cache and that solve the problem But why when I input a wrong integer operation code ,the code can work well even though I don't add the statement,"fflush(stdin);".

t0mm13b
  • 34,087
  • 8
  • 78
  • 110
surrey
  • 53
  • 4

1 Answers1

1

You should check return of scanf-

int c;
if(scanf("%d",&operation)==1){           //will return 1 if integer is entered
  switch(operation)
  {
    case 1:addBook();break;
    case 2:deleteBook();break;
    case 3:borrowBook();break;
    case 4:backBook();break;
    case 5:printAll();break;
    case 6:printAllBorrowed();break;
    case 7:findByNameAdapter();break;
    case 8:findByNumberAdapter();break;
    case 9:save();quit=0;break;
    case 0:system("cls");paintUI();break;
    default:printf("input error\n");break;
  }
  while((c=getchar()!='\n') && c!=EOF);
}

So , scanf fails if you enter a character and getchar will also clear the stdin.

ameyCU
  • 16,489
  • 2
  • 26
  • 41