【发布时间】: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