scanf 不是扫描 %c 字符而是跳过语句,这是为什么呢? [英] Scanf is not scanning %c character but skips the statement, why is that?

查看:12
本文介绍了scanf 不是扫描 %c 字符而是跳过语句,这是为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 switch 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("
GIVE THE VALUES OF THE TWO NUMBERS
");
    scanf(" %f %f",&a,&b);


    printf("
GIVE THE REQUIRED OPERATOR
");   

    //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("
GIVE A VALID OPRATOR
");

    }

    system("pause");        
    return 0;

但是当我在第二个 scanf 中的 %c 之前放置一个空格时,它可以工作,有人在讲述我发现令人困惑的空格

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 的值作为一个字符,如果我在 %c 之前放一个空格第二个 scanf 不是一个字符,它不以空格作为字符吗?

He said the second scanf is taking the value of 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?

但是在这个程序中它没有把 作为字符

But in this program it does not take the as the character

int main() 
{
    char a;
    printf("
give a char
");
    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 字符而是跳过语句,这是为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆