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

C语言开发文字RPG输入1后程序直接结束无输出Bug求助

C语言终端RPG选择逻辑失效问题修复

问题根因

一共两个会触发你描述现象的代码错误:

  • scanf 参数传参错误
    读取整数的scanf调用需要传入接收变量的内存地址,你的代码写的是scanf("%d" , yes_or_no);,直接传入了全局变量yes_or_no的初始值0,相当于把用户输入写入内存地址0的位置,触发未定义行为,直接导致程序异常退出,这就是输入1后程序直接结束的核心原因。
  • 标准输出缓冲区未刷新
    C语言终端输出默认是行缓冲机制,你写的两个结果提示字符串末尾都没有加换行符\n,内容会暂存在输出缓冲区不会立刻打印到屏幕,哪怕修复了scanf问题,也会出现看不到提示的情况。

修复方案

  1. 给scanf的第二个参数加上取地址符&,正确传入变量地址:
    scanf("%d", &yes_or_no);
    
  2. 给所有打印的提示文本末尾加上换行符\n,触发缓冲区刷新,保证内容立刻显示。

修复后完整代码

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

int yes_or_no;
int alive = 1;

void begin()
{
    //introduction of the game
    printf("Welcome to a terminal based rpg! REMEMBER: you can't save so this is a rougelike and a death means that you have to start from the beginning\n");
    printf("Just a small project made during a summer vacation\n");
    printf("Now , you start your journey!\n");

    //game starts
    printf("As you head out on your way , you suddenly see...\n");
}

void first_encounter()
{
    //1st enemy encounter
    //NOTE:all enemy encounters after the first 5 will be random
    printf("A goblin!\n");
    printf("what do you do?!\n");
    printf("You don't even have a single weapon! Maybe you can run away...\n");

    printf("Will you run away? (1(standing for yes)/0(standing for no))\n");
    
    //first yes or no question , the main mechanic of the game
    scanf("%d" , &yes_or_no);

    //checks the yes or no
    //if yes the game continues
    if (yes_or_no == 1)
    {
        printf("you run away\n");
    }

    //if no you are dead
    else if (yes_or_no == 0)
    {
        printf("you do not run away , and die\n");
        alive = 0;
        if (alive == 0)
        {
            exit(0);
        }
    }
}

int main(int argc, char const *argv[])
{ 
    begin();
    first_encounter();
    
    return 0;
}

额外优化提示:你代码注释里提到1/0做选择交互体验不好,后续可以改成读取字符输入,用'y'/'n'做选项,同时增加输入合法性校验,处理用户输入非0/1内容的异常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:30:51