Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue while creating a simple calculator in C

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-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading