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

如何在C程序中根据用户输入返回上一步?含输入异常处理需求

解决方案

针对日期输入的校验与回退/退出逻辑,你可以把日期选择环节改成循环校验的形式,同时处理输入错误后的缓冲区清理,避免死循环。修改后的代码片段如下:

while(l != 9){
    // 日期选择循环:直到输入有效或用户选择退出/回退
    int date_valid = 0;
    while(!date_valid && l != 9){
        printf("\nselect a date : \n");
        dates();
        printf("Date : ");
        // 检查scanf是否成功读取整数
        if(scanf("%d", &date) != 1){
            // 清空输入缓冲区的无效字符
            while(getchar() != '\n');
            printf("invalid input. press 1 to go back to previous step press 9 to exit\n");
            int choice;
            scanf("%d", &choice);
            if(choice == 1){
                // 返回上一步:回到外层循环起始
                date_valid = 1;
                continue;
            } else if(choice == 9){
                l = 9; // 设置退出标记
                date_valid = 1;
                continue;
            } else {
                // 选择无效,继续提示
                continue;
            }
        }
        // 校验日期是否为有效选项(1/2/3)
        if(date >=1 && date <=3){
            date_valid = 1; // 输入有效,跳出日期循环
        } else {
            printf("invalid input. press 1 to go back to previous step press 9 to exit\n");
            int choice;
            scanf("%d", &choice);
            if(choice == 1){
                date_valid = 1;
                continue;
            } else if(choice == 9){
                l = 9;
                date_valid = 1;
                continue;
            }
            // 其他选择继续循环
        }
    }
    if(l ==9) break; // 用户选择退出,终止外层循环

    // 日期输入有效,进入影院选择环节
    printf("\nselect a theatre : \n");
    theatre();
    printf("\ntheater : ");
    scanf("%d", &thter);
    if(thter==1){
        // 原有的影院处理逻辑
    }
}

关键说明

  • 输入合法性校验:通过scanf的返回值判断是否成功读取整数,避免非数字输入导致的死循环。
  • 缓冲区清理:输入无效时,用while(getchar() != '\n')清空输入缓冲区的残留字符,确保后续输入读取正常。
  • 回退/退出逻辑:输入无效时提示用户选择,按1回到流程起始,按9则设置退出标记终止所有循环。
  • 循环嵌套:用内层循环专门处理日期输入校验,直到输入有效或用户触发退出/回退,再进入后续的影院选择环节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:50:18