Scanf没有扫描%c字符但跳过声明,为什么?
我使用switch case语句编写了一个程序,并要求输入char但它不会在控制台窗口中询问char但是完全跳过它
int main() { float a, b, ans; char opr; printf("\nGIVE THE VALUES OF THE TWO NUMBERS\n"); scanf(" %f %f",&a,&b); printf("\nGIVE THE REQUIRED OPERATOR\n"); //no display(echo) on the screen //opr = getch(); //displays on the screen //opr = getche(); scanf("%c",&opr); switch(opr) { case '+' : ans = a+b; printf("%f", ans); break; case '-' : ans = ab; printf("%f", ans); break; case '*' : ans = a*b; printf("%f", ans); break; case '/' : ans = a/b; printf("%f", ans); break; case '%' : ans = (int)a % (int)b; printf("%f", ans); break; default : printf("\nGIVE A VALID OPRATOR\n"); } system("pause"); return 0;
但是当我在第二次scanf
在%c
之前放置一个空格时,有人正在讲述一些我发现令人困惑的空白
他说第二个scanf
将\n
的值作为一个字符,如果我在第二个scanf
中的%c
之前放一个空格不是一个字符而不是它将空格作为字符?
但是在这个程序中它不会将\n
作为角色
int main() { char a; printf("\ngive a char\n"); scanf("%c",&a); printf("%c",a); return 0; }
这真是令人困惑,可以帮助我,我想知道什么是错的。
每次使用此格式的scanf时:
scanf("%c",&a);
它留下了一个新行,将在下一次迭代中使用。 你提到的最后一个程序只有一个“scanf”。 尝试使用另一个scanf。 你会得到同样的问题。
所以为了避免空白,你必须写:
scanf(" %c",&opr);
格式字符串之前的空格告诉scanf忽略空格。 或者它更好用
getchar();
它将消耗你的所有换行符
问题是你在未使用的数字后离开\n
输入,然后由第二个scanf()
读取。 如果你检查opr
的值,你会看到它是’\ n’。
第二个程序将\n
作为角色。
也许你只是在输入其他字符之前没输入\n
。
示例(printf中的%c
更改为%d
以使其清除)
尝试在scanf之前添加fflush(stdin)。