Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

character input error in my C program?

Tags:

c

char

input

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.

like image 854
secureamd2 Avatar asked Feb 14 '17 13:02

secureamd2


People also ask

Does %s work in C?

%c and %s are part of the printf() functions in the standard library, not part of the language itself.

How do you declare a character in C?

In order to declare a variable with character type, you use the char keyword followed by the variable name. The following example declares three char variables. char ch; char key, flag;.

What does \0 represent in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string.


2 Answers

Just put a space before your enter operation's scanf() function's character format specifier and your program will work fine:

scanf( " %c" , &op );
like image 70
dhruw lalan Avatar answered Sep 29 '22 07:09

dhruw lalan


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 */
like image 41
RoadRunner Avatar answered Sep 29 '22 07:09

RoadRunner