Home > OS >  Issue while creating a simple calculator in C
Issue while creating a simple calculator in C

Time:12-26

I am creating a very basic calculator in C but the output is not coming as desired.

#include<stdio.h>
int main(int argc, char const *argv[])
{
    /* code */
    char ch;
    int a,b,p=0;
    scanf("%d",&a);
    while(1)
    {
        ch=getchar();
        if(ch==';')
        {
            p=2;
            break;
        }
        scanf("%d",&b);
        if(ch==' ')
        {
            a =b;
        }
        if(ch=='-')
        {
            a-=b;
        }
        if(ch=='*')
        {
            a*=b;
        }
        if(ch=='/' && b!=0)
        {
            a/=b;
        }
        if(ch=='/' && b==0)
        {
            printf("INVALID INPUT\n");
            p=2;
            break;
        }
    }

    if(p!=0)
        printf("%d",a);
    return 0;
}

The Output is always coming as the initial value which has been assigned to "a".

Output which is coming-

4
 
5
;
4

Expected output -

4
 
5
;
9

Can you please help me with this issue of why the expression is not getting evaluated correctly?

CodePudding user response:

The line

scanf("%d",&a);

will consume the first number from the input stream, but it will leave the newline character on the input stream.

Therefore, when you later call

ch=getchar();

it will read that newline character. It will not read the character.

If you want to read the character, then you can change that line to the following:

scanf( " %c", &ch );

This line will first discard all whitespace characters and will match the first non-whitespace character on the input stream.

Afterwards, your program will have the desired output:

4
 
5 
;
9

An alternative solution would be to discard the rest of the line after every call to scanf that uses the %d format specifier. That way, calling getchar immediately afterwards should read the character as intended.

You can discard the remainder of an input line using the following code:

//discard remainder of input line
{
    int c;

    do
    {
        c = getchar();

    } while ( c != EOF && c != '\n' );
}

Here is a more compact way of writing the same thing:

//discard remainder of input line
for ( int c; (c=getchar()) != EOF && c != '\n'; )
    ;

CodePudding user response:

The only problem is in scanning the inputs. As a tab or a new line must seperate the value supplied to scanf.

In short, just add '\n' at the end of scanf.

scanf("%d\n",&a); scanf("%d\n",&b);

this should do it.

  • Related