My code doesn't work, for some reason it skips a "fgets" instruction, and I've been relentlessly trying to fix this problem but I can't. I was in the middle of making a simple C game about rolling 3 dices and giving the result, the player would than guess if the next result would be higher, lower or the same as the last one.
Here's the code:
#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;
}
the fgets instruction that it's being skipped it's at the bottom, after the try again. Can someone explain me what am I missing? Even with scanfs it wouldn't work or using char instead of strings.
fgets()
buffer too small.
Entering "h\n"
needs at least 3 to save completely as a string.
Use a larger buffer.
After reading with fgets()
, lop off the potential '\n'
to make the following strcmp(guess,"s")
work.
char guess[100];
printf("\t\t\tWill the next one be h/l/s? ");
fgets(guess, sizeof guess, stdin);
guess[strcspn(guess, "\n")] = '\0';
Similar changes needed for fgets(enter...