do while循环中scanf_s仅触发一次输入,后续陷入死循环的原因咨询
问题原因及解决方法
核心原因
当你输入非整数内容(比如字母、汉字、带小数点的数值)时,scanf_s("%d", &yearPublished)会读取失败:
- 输入缓冲区里的无效字符不会被自动清空,后续循环中
scanf_s会反复尝试读取这些无效内容,始终无法成功获取有效整数。 yearPublished的值会保持初始垃圾值(或上一次的错误值),导致判断条件1 < yearPublished && yearPublished <= currentYear始终不成立,wrongInput一直为true,程序陷入死循环。
解决方法
- 检查
scanf_s的返回值:scanf_s会返回成功读取的变量个数,读取整数%d成功时返回1,失败返回0,以此判断输入是否有效。 - 清空输入缓冲区:读取失败时,用循环把缓冲区里的无效字符全部清空,避免影响下一次读取。
修改后的代码示例
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> // 假设currentYear和newMovie已定义 int currentYear = 2024; typedef struct { int yearPublished; } Movie; Movie* newMovie; int main() { bool wrongInput; int yearPublished; newMovie = (Movie*)malloc(sizeof(Movie)); do { printf("请输入出版年份:\n"); // 判断是否成功读取整数 int readResult = scanf_s(" %d", &yearPublished); if (readResult == 1 && 1 < yearPublished && yearPublished <= currentYear) { newMovie->yearPublished = yearPublished; wrongInput = false; printf("输入正确\n"); // DEBUG } else { printf("请输入有效的整数!\n"); wrongInput = true; // 清空输入缓冲区的无效字符 while (getchar() != '\n'); } } while(wrongInput); free(newMovie); return 0; }
内容的提问来源于stack exchange,提问作者Finn Österreicher
相关产品推荐
相关产品推荐

