scanf()的不采取从控制台输入 [英] scanf() not taking input from console

查看:494
本文介绍了scanf()的不采取从控制台输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h> 

int main() {

    float a, b, r;
    char op;

    scanf("%f",&a);
    scanf("%c",&op);
    scanf("%f",&b);
    scanf("%f",&r);

    switch(op) {

        case '+':
            r = a + b;
            printf("%f", r);
        break;

        case '-':
            r = a - b;     
            printf("%f", r);     
        break;

        case '*':
            r = a * b;    
            printf("%f", r);     
        break;

        case '/':
            r = a / b;     
            printf("%f", r);     
        break;

        default:
            printf ("Nekaj ne delas prav");

    }

    return 0;

}

这是给输出

Nekaj​​ NE德拉斯prav

"Nekaj ne delas prav"

和不采取任何输入。而不是使用'scanf()的,为什么它直接给出默认值作为输出,而不是使用switch语句。

and not taking any input. instead of using 'scanf()'and why it directly gives default value as output instead of using switch statement.

推荐答案

在您的code,请修改

In your code, please change

scanf("%f",&a);
scanf("%c",&op);
scanf("%f",&b);
scanf("%f",&r);

scanf("%f",&a);
scanf(" %c",&op);  //notice here
scanf("%f",&b);
scanf("%f",&r);

如果没有之前%C 前导空格,在 \\ n stoted由previous <大骨节病> ENTER 键preSS previous输入后,将被读取并视为%C 格式说明有效输入。所以,第二<​​code> scanf()的不会的询问的为单独的用户输入,该流程将继续到第三 scanf函数( )

Without the leading space before %c, the \n stoted by previous ENTER key press after previous input, will be read and considered as valid input for %c format specifier. So, the second scanf() will not ask for seperate user input and the flow will continue to the third scanf().

%C 的空白将消耗像字符所有前导空格S,其中包括 \\ n 由$ p $ stoted pvious <大骨节病> ENTER 键preSS和将仅考虑非空白输入。

The whitespace before %c will consume all leading whitespace like chars, including the \n stoted by previous ENTER key press and will consider only a non-whitespace input.

请注意:


  1. %F 格式说明读取和的忽略的主导 \\ n ,所以在这种情况下,你不需要在%F 来提供领先的空间明确。

  1. %f format specifier reads and ignores the leading \n, so in that case, you don't need to provide the leading space before %f explicitly.

的签名的main() INT主要(无效)

这篇关于scanf()的不采取从控制台输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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