运行时错误求助:scanf读取字符异常致循环提前终止
问题原因与解决办法
问题根源
你这段代码的问题出在输入缓冲区的换行符残留:
当你输入字符给ch_1后按回车,回车对应的换行符'\n'会留在输入缓冲区里。后续执行scanf("%c", &choice)时,它不会等待你手动输入,直接读取了缓冲区里的'\n',此时choice的值是'\n',不满足循环条件choice=='Y',所以循环直接终止。
解决方法
这里提供两种可靠的解决方式:
在
scanf的格式串前加空格
格式串开头的空格会让scanf自动跳过所有前置空白字符(包括换行、空格、制表符),直到读到第一个非空白字符。修改后的代码如下:#include<stdio.h> int main() { char ch_1, choice; do { printf("Enter letter:\n"); scanf("%c", &ch_1); // 判断大小写 if(ch_1 >= 65 && ch_1 <= 90) printf("\nuppercase\n"); else printf("\nlowercase\n"); printf("\nDo you want to enter another number?(Y/N)"); // 格式串前加空格,跳过残留的换行符 scanf(" %c", &choice); } while(choice == 'Y' || choice == 'y'); // 同时支持小写y,提升易用性 return 0; }用
getchar()清空缓冲区残留的换行符
在读取choice之前,调用getchar()吃掉缓冲区里的换行符:#include<stdio.h> int main() { char ch_1, choice; do { printf("Enter letter:\n"); scanf("%c", &ch_1); if(ch_1 >= 65 && ch_1 <= 90) printf("\nuppercase\n"); else printf("\nlowercase\n"); printf("\nDo you want to enter another number?(Y/N)"); // 吃掉缓冲区里的换行符 getchar(); scanf("%c", &choice); } while(choice == 'Y'); return 0; }
额外修正建议
- 代码里的
printf语句存在字符串未闭合的问题,比如printf("\nuppercase);应该改为printf("\nuppercase\n");,需要补上闭合的双引号,避免编译错误。 - 尽量使用
int main()替代void main(),并添加return 0;,这是符合C语言标准的写法。
内容的提问来源于stack exchange,提问作者Bhagat Singh
相关产品推荐
相关产品推荐

