【问题标题】:scanf seems to break my code (C programming) [duplicate]scanf 似乎破坏了我的代码(C编程)[重复]
【发布时间】:2022-01-04 00:14:23
【问题描述】:

我正在为我的 C 编程课程编写一个基于文本的冒险游戏,但无论出于何种原因,每当我尝试使用“scanf”来获取玩家的输入时,代码似乎都会中断。一切都会完美地打印到控制台上,但是当我包含“scanf(”%d“,playerInput)”行时,什么都不会打印出来,程序将无休止地运行。有人知道为什么会这样吗?这是我的代码:

#include <stdbool.h>
#include <stdio.h>

int main()
{
    printf("~ Doctor Crowley: Master of Death ~\n"); //Titlecard

    //Introductory narration =================================================================================================
    printf("\n- Narrator -\n");
    printf("You are Doctor Jonathan Crowley, an archeologist and wizard from the Arcane University in Aeternum.\n");
    printf("You awaken in your classroom on the first floor of the University. Last you remember, you were in your office\n");
    printf("on the sixth floor of the University.\n");

    // Player Actions (1) ========================================================================================================================
    printf("\n1. Stand up\n");
    printf("2. Look around\n");
    printf("-------------------------------------------\n");

    int playerInput; //player input variable
    printf("--> ");
    scanf("%d", &playerInput);

    return 0;
}

【问题讨论】:

  • 行缓冲的输出在没有被换行符终止时可能会被缓存。当您输入一个值时,它可能应该在退出之前刷新缓冲区。以\n 结束 printf 或明确地 fflush(stdout);在调用 scanf 之前。
  • 如果您输入一个数字并按 Enter 会发生什么?

标签: c


【解决方案1】:

首先确保在scanf 中的任何变量之前写入'&'。如果你不写,它会崩溃并迫使你结束程序。然后,当您在代码中编写时,它只输入数字并将其放入变量 playerInput 中,仅此而已。你在 scanf 之后没有打印任何东西,所以在那之后什么都不会发生。例如你可以写 printf("%d",playerInput);之后,它将打印 playerInput 中的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2017-09-30
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多