我已经解决这个问题几个小时了,但似乎无法解决这个问题。我相信这可能是由于 startgame() 中的 scanf 在完成后创建了一个新行字符,但我在网上读到的避免此问题的方法都没有起作用。我可以得到一些帮助来理解和解决这个问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int startgame();
int main(){
char name[256];
int dexterity, endurance, strength, intelligence, health = 0;
int endingtokens = 0;
startgame();
gets(name);
return 0;
}
int startgame(){
char decision [100];
do{
printf("Welcome to 'A Week in Basilisk'. Type 'start' to continue.\n");
scanf("%s", decision);
if(strcmp(decision, "start") == 0){
printf("starting...");
}
else if (strcmp(decision, "quit") == 0){
printf("quiting...");
exit(0);
}
}
while(strcmp(decision, "start") != 0);
return 0;
}
我尝试用 fgets 替换 scanf,向 scanf 和所有 if 语句条件添加空格,然后添加 scanf/all if 语句条件。
线路
scanf("%s", decision);
不会读取整行输入。它将至少在输入缓冲区内的行末尾留下换行符。这意味着该行
gets(name);
不会等待用户输入,而是读取
scanf
留在缓冲区中的剩余行,包括换行符,并立即返回。
如果您不希望这样,则可以通过在调用
scanf
函数之前立即运行以下代码来丢弃 gets
留在输入缓冲区中的其余行:
int c;
while ( (c=getchar()) != '\n' && c != EOF )
;
此循环将一次读取并丢弃一个字符,直到读取并丢弃换行符。