0

I'm trying to make a program that is basically a dice roll between two players. Starting with the first player, they take turns guessing what the result of the dice roll will be, and get awarded points if they guess correctly. The problem is, when run, the program ignores the scanf to check if the players want to play another round, and exits the do while loop. I have had this problem before and found no satisfying answer, what might the issue be? (I'm a beginner so forgive me if I have a stupid mistake)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
    int n, p1, p2, turn;
    char answer;

    p1=0;
    p2=0;

    do
    {   
        //checking if player guesses correctly
        printf("Place bet\n");
        scanf("%d", &n);

        if (n-1==rand()%6 || turn==1)
        {
            printf("Player 1 wins!\n");
            p1++;
        }
        else if (n-1==rand()%6 || turn==2)
        {
            printf("Player 2 wins!\n");
            p2++;
        }
        else 
        {
            printf("Bad guess!\n");
        }

        //checking if players want to play another round
        printf("Play another round?\n");
        scanf("%c", &answer);

        //changing turns
        if (turn>1)
        {
            turn=1;
        }
        else 
        {
            turn++;
        }
    }while (answer=='y');

    printf("Final scores are:\nPlayer 1 got %d points.\nPlayer 2 got %d points\n", p1, p2); 
}
aris1998
  • 1
  • 1
  • You wanted scanf %d to read a single character, and it tried to, but when you tried to type that single character at it, before the rest of the input system would accept it, you had to hit the RETURN key, too. scanf read only the one character, but that extra newline was still sitting in an input buffer somewhere, and it's that extra newline (seemingly representing a phantom blank line) which was received by your later input call. – bruceg Dec 16 '16 at 01:38
  • 1
    `scanf(" %c ", &answer)` to ignore the whitespace around the answer char. see manpage for more details. – Petr Skocik Dec 16 '16 at 01:42

0 Answers0