do while 循环只执行 scanf_s(" %d", &variable);一次

问题描述 投票:0回答:1

当遇到 do while 循环时,我只被要求输入一次,然后就陷入无限循环。有人知道为什么吗?

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);
c scanf do-while c11
1个回答
0
投票

我刚刚找到了解决由于未清除输入缓冲区而导致的问题的方法:

在 while 循环末尾添加以下内容可以解决这个问题

// Clear the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
© www.soinside.com 2019 - 2024. All rights reserved.