1

I just started coding so sorry for the stupid question. This is C programming. When the user inputs Y, the code runs as intended. If the user inputs N or any other character, the program loops but it repeats the same line twice for some reason. For example:

Input: Y
Output: The game will now start!
Input: N
Output: Waiting...
Would you like to start the game? <Y/N>:
 is not a valid response
Would you like to start the game? <Y/N>:

As you can see the line doubles, how do I fix this?

do {
    printf("Would you like to start the game? <Y/N>: ");
    scanf("%c", &cGameStart);
    if (cGameStart == 'Y')
        printf("\nThe game will now start!\n");
    if (cGameStart == 'N')
        printf("\nWaiting...\n\n");
    if ((cGameStart != 'Y') && (cGameStart != 'N'))
        printf("%c is not a valid response\n", cGameStart);
} while (!(cGameStart == 'Y'));
Kitty Miao
  • 23
  • 3
  • Offtopic, but: Your indentation is a bit confusing. I'd advise you to keep the different `if` statements on the same indentation level because currently it looks like you only check for `N` if `cGameStart == 'Y'` (which is not true) – lucidbrot Aug 16 '20 at 14:19
  • @BlayerBond I think they work like KittyMiao expects - basically three independent checks. But I am also in favor of always using curly braces – lucidbrot Aug 16 '20 at 14:20
  • 2
    @lucidbrot, you are right; he should have used the `if {} else if {} and else` construction for clarity then. The tabs were misleading. –  Aug 16 '20 at 14:22
  • the code works fine https://godbolt.org/z/vMbjdz if you consider the `\n` char left in the buffer. – 0___________ Aug 16 '20 at 14:25
  • https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer – Alex Lop. Aug 16 '20 at 14:30

1 Answers1

1

The comment are rather irrelevant to the problem.

The problem is the \n character left in the buffer by scanf. Eat it and it will work as intended.

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

int main(void)
{
    char cGameStart;
    do {
        printf("Would you like to start the game? <Y/N>: ");
        scanf("%c", &cGameStart);
        if (cGameStart == 'Y')
            printf("\nThe game will now start!\n");
        if (cGameStart == 'N')
            printf("\nWaiting...\n\n");
        if ((cGameStart != 'Y') && (cGameStart != 'N'))
            printf("%c is not a valid response\n", cGameStart);
        fgetc(stdin);
    } while (!(cGameStart == 'Y'));
    printf("Game started\n");
}
0___________
  • 60,014
  • 4
  • 34
  • 74