简体   繁体   中英

character input error in my C program?

I am new to C programming, I have made a simple calculator program in C.
The program runs but doesn't work, it works till value for b is entered after then when character input comes it doesn't ask for the input. I don't know why this is happening but is there any fix?

here's my code:

#include <stdio.h>
int main()
{
    float a,b;
    char op;
    printf("enter a: ");
    scanf("%f",&a);
    printf("enter b: ");
    scanf("%f",&b);
    printf("enter operation: ");
    scanf("%c",&op);
    switch(op)
    {
        case '+':
            printf("\n%.2f %c %.2f = %.2f",a,op,b,a+b);
            break;
        case '-':
            printf("\n%.2f %c %.2f = %.2f",a,op,b,a-b);
            break;
        case '*':
            printf("\n%.2f %c %.2f = %.2f",a,op,b,a*b);
            break;
        case '/':
            printf("\n%.2f %c %.2f = %.2f",a,op,b,a/b);
            break;
        default:
            printf("invallid input!!");
    }
    return 0;
}

The program seems to be absolutely correct but still there is something there I am missing. Answers are appreciated.

只需在输入操作的scanf()函数的字符格式说明符前放置一个空格 ,程序便可以正常工作:

scanf( " %c" , &op );

When using scanf() , it will leave behind a \\n character in the input buffer. The next scanf() will keep this newline and store it. You need to either add a space to scanf() :

scanf(" %c", &op); /* to skip any number of white space characters */

Or consume the character instead with getchar() . The function getchar() returns int and EOF on error It can be used this way:

int op = getchar()

Which stores the character found in op . You could also just add getchar() after your scanf() calls, which will consume the leftover \\n character.

Note: It is good practice to check result of scanf() . You should write instead:

if (scanf(" %c", &op) != 1) {
    /* oops, non character found. Handle error */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM