问题描述
我使用开关case语句写了一个程序,要求输入一个字符,但它不要求在控制台窗口中的字符,但完全跳过它。
I wrote a program using switch case statement and asked for a char for input but it does not ask for the char in the console window but skips it completely
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 = a-b;
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;
但是当我在第二把空间之前%C
scanf函数
它的工作原理有人讲了一些关于空白,我发现混乱
but when i put a space before %c
in the second scanf
it works someone was telling something about a whitespace which i found confusing
他说,第二个 scanf函数
正在的\\ N值
作为一个字符,如果我把一个空间前%C
第二 scanf函数
不是一个字符,不将其乘坐空间作为字符?
He said the second scanf
is taking the value of \n
as a character and if i put a space before %c
in the second scanf
isn't that a character and doesn't it take the space as the character?
不过,这个计划不会采取 \\ n
作为字符
But in this program it does not take the \n
as the character
int main()
{
char a;
printf("\ngive a char\n");
scanf("%c",&a);
printf("%c",a);
return 0;
}
这是真的混淆可以在任何帮助我,我想了解什么是错的。
This is really confusing can any on help me i want to learn what is wrong.
推荐答案
每次使用scanf的这种格式时间:
Every time you use scanf with this format :
scanf("%c",&a);
它离开,这将在下一迭代中消耗的换行符。
你提到的日最后一个节目只有一个scanf函数。尝试使用其他scanf函数。你会得到同样的问题。
it leaves a newline which will be consumed in the next iteration.Th last program that you mentioned have only one "scanf". try to use another scanf. you will get the same problem.
所以要避免空格你必须写:
so to avoid white spaces you have to write :
scanf(" %c",&opr);
格式字符串前的空格告诉scanf函数忽略空格。或它更好地使用
the space before the format string tells scanf to ignore white spaces. Or its better to use
getchar();
这会消耗你所有的换行
It will consume all your newline
这篇关于scanf函数未扫描%C字符,但跳过的说法,这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!