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;
}

`

tanvir
  • 1
  • 1
  • a '\n' character is caught by getchar, you need to clear the input buffer before you call getchar. – anastaciu Sep 10 '20 at 10:03
  • Just toss in an empty `getchar();` line between `scanf` and `ch=getchar();`. See duplicate links for an explanation why. – Lundin Sep 10 '20 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](https://stackoverflow.com/a/15228406/6865932) to validate the inputs. – anastaciu Sep 10 '20 at 10:09

0 Answers0