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

如何解决C程序无法根据用户输入更改终端输出的问题?

问题分析与修复方案

核心问题

  1. 数组缓冲区溢出:Q0ans定义为char Q0ans[3];,但字符串"Yes"需要4字节存储空间(3个可见字符 + 1个字符串终止符\0)。用scanf读取输入时会超出数组边界,破坏内存,导致strcmp的比较结果异常。
  2. scanf参数错误:Q0ans是数组名,本身就是指向数组首元素的指针,不需要加&符号,加&会导致类型不匹配,触发未定义行为。

修改后的代码

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

int main(){
    char Q0real[]="Yes", Q0ans[4]; // 调整数组大小为4,容纳完整字符串
    printf("Welcome to my game v0.1\n");
    sleep(3);
    printf("Just answer the questions to win!\n");
    sleep(3);
    printf("Do you understand? (Yes/No)\n"); // 修正提示文本的重复问题
    scanf("%s", Q0ans); // 移除多余的&符号
    int result = strcmp(Q0real, Q0ans);
    if(result == 0){
        printf("Okay. First Question.\n\n");
        sleep(2);
    }else{
        printf("GET OUT, RIGHT NOW. LEAVE.\n");
        sleep(10);
        return 0;
    }
    return 0; // 补充标准返回值,符合C语言规范
}

额外说明

  • 调整提示文本为(Yes/No),符合逻辑(原提示重复"Yes"无意义);
  • 补充main函数末尾的return 0;,满足C标准对main函数返回值的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:10:33