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

输入正确名称后C语言程序循环重启问题求助

问题排查与修复方案

核心问题1:字符串字面量格式错误

你的代码中所有printf里的换行都是直接在字符串中换行,而非使用C语言标准的\n转义字符,这会导致编译器解析错误(比如未终止的字符串常量),进而引发程序行为异常,这是输入"William"后进入异常循环的直接原因。

核心问题2:生日验证逻辑完全颠倒

当前代码中,输入错误的生日会退出循环,输入正确的生日反而提示错误并继续循环,完全违背需求逻辑。

修复后的完整代码

#include <stdio.h>
#include <string.h>

int main()
{
    char correctName[] = "William";
    char correctBirthday[] = "(01/01/2000)";

    char name[100];
    char birthday[100];
    char response[10];

    // 姓名验证循环
    while (1) {
        printf("Hello, please enter your name: ");
        // 限制输入长度,避免缓冲区溢出
        scanf("%99s", name);

        if (strcmp(name, correctName) == 0) {
            printf("Thank you.\n");
            break;
        } else {
            printf("Searching... \n\n");
            printf("Invalid user. Please enter the correct name.\n\n");
        }
    }

    // 生日验证循环
    while (1) {
        printf("I must ask you to confirm your birthdate with me so I can assure that it is you.\n");
        printf("Please do so in this format: (MM/DD/YYYY). \n");
        scanf("%99s", birthday);

        if (strcmp(birthday, correctBirthday) == 0) {
            // 验证通过,退出循环
            printf("Birthdate confirmed.\n");
            break;
        } else {
            printf("Searching... \n\n");
            printf("Invalid birthdate. Please try again.\n\n");
        }
    }

    printf("Hello William!\n\n");

    printf("Do you wish to proceed? (yes/no): \n");
    scanf("%9s", response);

    if (strcmp(response, "yes") == 0) {
        printf("Great! let's get started.\n");
    } else {
        printf("Confirmed, have a nice day.\n");
    }
    return 0;
}

关键修复点说明

  • 所有字符串中的换行替换为\n转义字符,确保编译器正确解析字符串。
  • 颠倒生日验证的判断逻辑:输入正确生日时退出循环,错误时重复询问。
  • 在scanf中添加长度限制(如%99s),避免缓冲区溢出风险。
  • 调整提示文本,使其更符合逻辑(比如错误姓名提示改为"请输入正确姓名",错误生日提示改为"生日无效,请重试")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:19:58