繁体   English   中英

“scanf”语句不执行?

[英]the "scanf" statement doesn't execute?

我的代码如下:

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;
}

当我在“操作”中输入一个整数时,代码运行良好。但是当我故意输入一个字符值时,代码会陷入无限循环并一直打印“输入错误”。当我调试时,我发现在我故意输入一个字符值后,语句"scanf("%d",&operation)" 不再被执行,所以操作码总是错误的。有人告诉我添加一个语句,"fflush (stdin);",清除输入缓存,解决问题但是为什么当我输入错误的整数操作代码时,即使我不添加语句“fflush(stdin);”,代码也能正常工作。

您应该检查scanf return -

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);
}

因此,如果您输入一个字符,则scanf失败,并且getchar也会清除stdin

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM