当遇到 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);
我刚刚找到了解决由于未清除输入缓冲区而导致的问题的方法:
在 while 循环末尾添加以下内容可以解决这个问题
// Clear the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);