You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何输入0-7外内容时C语言while循环会无限运行?

问题:C语言while循环输入非法值时无限运行的原因

先看这段代码:

while (option){
    printf("\nPress 0 : Exit\nPress 1 : Enqueue\nPress 2 : Dequeue\nPress 3 : Peek\nPress 4 : Isempty\nPress 5 : Isfull\nPress 6 : Size\nPress 7 : Display\n");
    scanf("%d", &option);

    if(option == 1){
        Enqueue();
    }else if(option == 2){
        Dequeue();
    }else if(option == 3){
        Peek();
    }else if (option == 4){
        Isempty();
    }else if(option == 5){
        Isfull();
    }else if(option == 6){
        Size();
    }else if(option == 7){
        Display();
    }else if(option == 0){
        printf("\nBYE\nBYE\nBYE");
    }else{
        printf("\nWRONG INPUT!!");
    }
}

为什么输入0-7以外的内容会无限循环?

核心原因在scanf("%d", &option)的工作机制:

  • 当输入的不是整数(比如字母、符号),scanf没法把它解析成int类型,不会修改option的原有值,而且这个非法输入会留在输入缓冲区里,不会被清空。
  • 下一次循环时,scanf会直接读取缓冲区里残留的非法内容,再次解析失败,option还是保持之前的非0值(只有输入0才会让循环条件while(option)不成立),于是循环反复执行,一直输出"WRONG INPUT!!"。

解决办法

要处理非法输入,得做两件事:检查scanf的返回值,清空输入缓冲区的残留内容。修改后的代码如下:

while (option){
    printf("\nPress 0 : Exit\nPress 1 : Enqueue\nPress 2 : Dequeue\nPress 3 : Peek\nPress 4 : Isempty\nPress 5 : Isfull\nPress 6 : Size\nPress 7 : Display\n");
    // 保存scanf的返回值,成功读取整数时返回1,失败返回0
    int scan_result = scanf("%d", &option);

    // 处理非法输入的情况
    if(scan_result != 1){
        // 清空输入缓冲区,直到读到换行符
        while(getchar() != '\n');
        printf("\nWRONG INPUT!!");
        continue; // 跳过后续判断,直接进入下一轮循环
    }

    if(option == 1){
        Enqueue();
    }else if(option == 2){
        Dequeue();
    }else if(option == 3){
        Peek();
    }else if (option == 4){
        Isempty();
    }else if(option == 5){
        Isfull();
    }else if(option == 6){
        Size();
    }else if(option == 7){
        Display();
    }else if(option == 0){
        printf("\nBYE\nBYE\nBYE");
    }else{
        printf("\nWRONG INPUT!!");
    }
}

内容的提问来源于stack exchange,提问作者Data Scientist to be

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:50:07