输入微小改动导致C语言日期校验程序异常跳过输入
问题原因
你代码中scanf使用了%i作为格式化占位符,这是触发输入跳过的核心原因:
%i会自动识别输入值的进制:带0x前缀按十六进制解析,带0前缀按八进制解析,无前缀才按十进制解析- 八进制的合法数字仅为0~7,当你输入
09时,前置的0触发八进制解析逻辑,但后续的9属于非法八进制字符,scanf会直接匹配失败:既不会给对应变量赋值,也不会清理输入缓冲区里残留的9 - 后续的
scanf调用会直接读取缓冲区残留的非法字符,再次匹配失败,就出现了跳过输入环节的现象
解决方法
把所有scanf语句中的%i替换为%d即可。%d会固定将输入内容按十进制解析,不会受前置0影响,输入09时会正常识别为十进制数值9,完全适配日期输入的需求。
修改后的核心输入代码示例:
printf("Enter the day of first date: "); scanf("%d", &date[0]); printf("Enter the month of first date: "); scanf("%d", &date[1]); printf("Enter the year of first date: "); scanf("%d", &date[2]); printf("Enter the day of the second date: "); scanf("%d", &secondDate[0]); printf("Enter the month of the second date: "); scanf("%d", &secondDate[1]); printf("Enter the year of the second date: "); scanf("%d", &secondDate[2]);
内容的提问来源于stack exchange,提问作者Jbb
相关产品推荐
相关产品推荐

