我的代码不工作,由于某些原因,它跳过了一个 "fgets "指令,我一直在不厌其烦地试图解决这个问题,但我不能。我正在做一个简单的C游戏,关于掷3个骰子,并给出结果,玩家会比猜测下一个结果是更高,更低还是与上一个相同。
下面是代码。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(int argc, char *args[]) {
printf("__________________________OPEN THE GAME!_________________________\n");
printf("\tThe rules are simple,\n\twe are gonna roll 3 dices and\n\tgive you the result.\n\tYou're then going to guess if\n\tthe next roll is gonna be\n\thigher(h), lower(l) or same(s)!\n");
//char ready[3];
//printf("\t\t\tAre you ready? ");
//fgets(ready, 2, stdin);
int roll1;
int roll2;
int roll3;
char enter[] = "y";
while(strcmp(enter, "n"))
{
roll1 = rand()%6 + 1;
roll2 = rand()%6 + 1;
roll3 = rand()%6 + 1;
printf("First roll!\n%d\n\n", roll1);
printf("Second roll!\n%d\n\n", roll2);
printf("Third roll!\n%d\n\n", roll3);
int firstResult = roll1 + roll2 + roll3;
printf("Result: %d\n", firstResult);
char guess[2];
printf("\t\t\tWill the next one be h/l/s? ");
fgets(guess, 2, stdin);
int result = (rand()%6 + 1) + (rand()%6 + 1) + (rand()%6 + 1);
if (((result == firstResult) && (strcmp(guess,"s"))) || ((result > firstResult) && (strcmp(guess,"h"))) || ((result < firstResult) && (strcmp(guess,"l"))))
{
printf("°°°°°°°°°°°Correct, you win!°°°°°°°°°°°\n");
printf(" The result was: %d\n", result);
}
else
{
printf("\tI'm sorry, the new roll is %d :(\n", result);
}
printf("\tTry again?(y/n)");
fgets(enter, 2, stdin);
firstResult = result;
}
printf("\t\t\tGG, come back when you want to test your luck B)\n");
return 0;
}
fgets指令被跳过,在底部,在再试一次之后. 谁能解释一下,我漏掉了什么? 即使用scanfs也不行,或者用char代替字符串.
fgets()
缓冲区太小。
输入 "h\n"
至少需要3个才能完全保存为一个字符串。
使用更大的缓冲区。
读取后,用 fgets()
,切断潜在的 '\n'
做出以下决定 strcmp(guess,"s")
工作。
char guess[100];
printf("\t\t\tWill the next one be h/l/s? ");
fgets(guess, sizeof guess, stdin);
guess[strcspn(guess, "\n")] = '\0';
需要进行类似的改变 fgets(enter...