D
D
dyrtage62020-08-15 10:27:56
C++ / C#
dyrtage6, 2020-08-15 10:27:56

Why is the 'menu' shown 2 times?

Hello! Started learning the C language for programming robots. I decided to make the game "Hangman", but there is a small problem. For some reason the menu is shown twice after I enter something. I can't understand the reason. 5f378e41dc312724768890.jpeg

Here's what that piece of code looks like -

void main() {
    char choice;

    printf("Hello! You got into the 'Hangman' game\n");
    while (choice != '0') {
        printf("\n0. Exit\n1. Phone brands\n2. Programming languages\n3. Kinds of sports\n");
        printf("Enter what you want to guess: ");
        scanf("%c", &choice);

        if (choice == '0') {
            printf("\nGoodBye...");
            break;
        } else if (choice == '1') 
            printf(SevenAttempt);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-08-15
@dyrtage6

For some reason the menu is shown twice after I enter something.
scanf("%c", &choice);

Because this scanf reads a single character from the input stream, and to enter, for example, 1, you need to press '1', followed by 'enter'. '1' will remain itself and be read by the first scanf, while 'enter' will become '\n' and will be read by the second scanf.
To avoid this, you can read this:
scanf(" %c%*[^\n]", &choice);
Space before %cswallows all whitespace characters, %*[^\n]swallows the tail of the line after the first non-whitespace character read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question