0

In this program i can take two integers but cannot take char as input.. what shuold i do in this situation to take both int and char? i would like to make a simple calculator where i can choose the operator such as +,-,/,* to perform calculation.

#include <stdio.h>
#include <stdlib.h>
//Adding two real numbers using character type variable

int main()
{
    int a,b,c;
    char ch;
    printf("Enter two number: \n");
    scanf("%d %d", &a,&b);
    ch=getchar();

    if((ch=='+')){
        c=a+b;
        printf("%d", c);
    }
    else{
        printf("wrong!");
    }

    return 0;
}

`

3
  • a '\n' character is caught by getchar, you need to clear the input buffer before you call getchar. Commented Sep 10, 2020 at 10:03
  • Just toss in an empty getchar(); line between scanf and ch=getchar();. See duplicate links for an explanation why. Commented Sep 10, 2020 at 10:07
  • Or use scanf("%d %d\n", &a,&b);, in any case the clear routine you can find in the duplicates is more robust and will clear any number of extra characters in the input buffer. And don't forget to check scanf return value to validate the inputs. Commented Sep 10, 2020 at 10:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.