为何C语言中scanf函数无法第二次读取字符?
scanf第二次不等待输入的原因及解决办法
问题的核心是输入缓冲区残留的换行符导致的:
当你第一次输入字符并按下回车键时,输入的字符会被scanf("%c", &a)读取,但回车键对应的\n(换行符)会留在输入缓冲区中。第二次调用scanf("%c", &b)时,它会直接读取缓冲区里的这个\n,不会等待你手动输入,所以程序直接执行后续的printf语句。
解决办法
这里提供两种可靠的解决方式:
- 在第二个
scanf的格式控制串前添加空格,空格会自动匹配并跳过缓冲区中的所有空白字符(包括换行、空格、制表符):scanf(" %c", &b); - 在第一个
scanf之后,调用getchar()来吃掉缓冲区里的换行符:scanf("%c", &a); getchar(); // 读取并丢弃缓冲区的换行符
修改后的完整代码示例
#include <stdio.h> int main() { printf("--Mathematical operations on character to get other character--\n"); char a, b; printf("Enter the 1st character: \n"); scanf("%c", &a); getchar(); // 清除缓冲区的换行符 printf("Enter the 2nd character: \n"); scanf("%c", &b); printf("\nThe ASCII equivalent for addition of %c and %c is %c\n", a, b, (a + b)); printf("\nThe ASCII equivalent for subtraction of %c and %c is %c\n", a, b, (a - b)); printf("\nThe ASCII equivalent for multiplication of %c and %c is %c\n", a, b, (a * b)); printf("\nThe ASCII equivalent for division of %c and %c is %c\n", a, b, (a / b)); printf("\nThe ASCII equivalent for modular division of %c and %c is %c\n", a, b, (a % b)); return 0; }
内容的提问来源于stack exchange,提问作者Daksh
相关产品推荐
相关产品推荐

