scanf(“%d",a) 带有“while";语法绕过scanf [英] scanf("%d",a) with a "while" grammar bypass the scanf

查看:71
本文介绍了scanf(“%d",a) 带有“while";语法绕过scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有初始化 ("mod=0") ,这段代码会无限循环.我不明白为什么这段代码会循环,即使我使用了 getchar();擦除缓冲区.当我先输入1",然后输入a"时,就会出现无限循环.有人可以帮助我了解这种情况吗?

if there is no initialization ("mod=0") , this code go infinite loop. I can't understand why this code go loop, even if I used getchar(); to erase the buffer. when I typed "1" first, and typed "a" next, there goes an infinite loop. Can anybody help me with understanding this situation?

int main()
{
    srand((unsigned)time(NULL));
    int mod = 0;
    int val = 0;
    do {    
        printf("\t-----------------------------\n");
        printf("\t|%5s %5s %5s %5s|\n", "1.create", "2.modify", "3.print", "4.quit");
        printf("\t|%15s","Input command  : ");
        scanf("%d", &mod);
        printf("\t-----------------------------\n");
        switch (mod){
        case 1:     random();           val++;      break;
        case 2:     if(val != 0) { modify();    break; }
        case 3:     if(val != 0) { print();     break; }
        default:    getchar(); printf("\tUnknown Command!! Retry!! \n");    break;
        }
    } while (mod != 4);
}

我用 Visual Studio 2015 编译了这段代码.

I compiled this code with Visual Studio 2015.

推荐答案

当您输入 a 时,mod 作为 scanf() 期望 %dint.所以它不是读入mod.所以 mod 剩下的是上次迭代输入的 mod 的值.

When you input a, it's an invalid input for mod as scanf() expects an int for %d. So it's not read into mod. So the mod is left with the value of mod inputted in the previous iteration.

它进入无限循环的原因是因为 scanf() 不会丢弃无效输入.因此反复尝试读取 a 并失败并继续循环.

And the reason it goes in an infinite loop is because scanf() doesn't discard the invalid input. So repeatedly attempts to read a and fails and loop goes on.

检查 scanf() 的返回值并丢弃任何无效输入.scanf() 在读取用户输入方面是出了名的糟糕,并且正确处理输入失败通常更难使用它.

Check the return value of scanf() and discard any invalid input(s). scanf() is notoriously bad for reading user input and proper handling input failures is generally harder using it.

更好的方法是使用fgets() 然后使用 sscanf().

A better approach is to read a line input using fgets() and then parse it using sscanf().

do {
    ...

    printf("\t|%15s","Input command  : ");

    fgets(line, sizeof line, stdin);
    char *p = strchr(line, '\n');
    if(p) *p = 0; /* remove tailing newline, if present */
    if( sscanf(line, "%d", &mod) != 1) {
       printf("Invalid input\n");
       continue;
    }

    printf("\t-----------------------------\n");
    ....

   }while (mod != 4);

这篇关于scanf(“%d",a) 带有“while";语法绕过scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆