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

C语言自助照相亭程序错误输入重复提示问题修复求助

问题描述

开发C语言模拟自助照相亭程序时,输入错误的照片格式选项后,程序会重复两次输出错误提示和输入请求,运行输出如下:

Select photo format(A, B, C, or D):f

Please insert a correct input
                                      Select photo format(A, B, C, or D):
            Please insert a correct input
                                      Select photo format(A, B, C, or D):

源代码中函数内的while循环运行正常,但无法定位该问题原因,需要修复方案。

问题根源
  1. 输入缓冲区残留换行符:使用scanf("%c", &frameOption)读取字符时,用户输入错误选项(如f)并按下回车后,输入缓冲区会保留f\n两个字符。第一次scanf读取f并触发default分支输出错误提示;循环再次执行时,scanf直接读取缓冲区中残留的\n,该字符不属于合法选项范围,再次触发default,导致两次错误提示。
  2. 变量类型不匹配:frameOption被定义为int类型,但实际存储的是字符值,虽不影响运行,但不符合代码语义规范。
修复方案

1. 修正字符读取逻辑

在scanf的%c格式符前添加空格,让scanf自动跳过输入缓冲区中的空白字符(包括换行符、空格等),避免误读残留的换行符:

scanf(" %c", &frameOption);

2. 修正变量类型

将frameOption的类型从int改为char,符合存储字符的语义:

// 原定义:int frameOption,paymentMethod,amount;
char frameOption;
int paymentMethod, amount;

完整修改后的核心代码片段

int main()
{
    int i;
    char frameOption; // 修正为char类型
    int paymentMethod, amount;
    int row,column;
    int A[1]={1};
    int B[2]={1,2};
    int C[3]={1,2,3};
    int D[2][2]={{1,2},{3,4}};
    int E[4]={1,2,3,4};

    printf("\t\t\t\t\tWelcome to photobooth!\n");
    printf("\t\t\t\t\t Press Enter to start\n\n");

    while (getchar() != '\n');

    // ... 省略菜单打印代码 ...

    do
    {
        printf("\t\t\t\t\t  Select photo format(A, B, C, or D):");
        scanf(" %c", &frameOption); // 添加空格跳过空白字符

        switch(frameOption)
        {
            // 原有case分支逻辑保持不变
            case 'A':
                // ...
                break;
            // ... 其他case ...
            default:
            {
                printf("\n\t\tPlease insert a correct input\n");
                break;
            }
        }

    }
    while(frameOption != 'A' && frameOption != 'B' && frameOption != 'C' && frameOption != 'D' && frameOption != 'E');
    
    // ... 后续代码保持不变 ...
}
修复效果验证

修改后,输入错误选项时,程序只会输出一次错误提示,随后重新请求输入,不会出现重复提示的问题,符合预期逻辑。

内容的提问来源于stack exchange,提问作者hsnadyna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:23:26