do while loop does only execute scanf_s(" %d", &variable); once

51 Views Asked by At

When running into the do while loop my I'm only asked for input once and run into an endless loop afterwards. Does someone know why?

do {
        printf("Insert the year published: \n");
        scanf_s(" %d", &yearPublished);
        if (1 < yearPublished && yearPublished <= currentYear) {
            newMovie->yearPublished = yearPublished;
            wrongInput = false;
            printf("Correct input"); //DEBUG
        } else {
            printf("Please enter a valid integer number!\n");
            wrongInput = true;
        }
} while(wrongInput);
1

There are 1 best solutions below

0
Finn Österreicher On

I just found a solution for the problem which is caused from not clearing the input buffer:

with adding the following at the end of the while loop this can be fixed

// Clear the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);