-2

I am making a simple calculator using if else statement, but my 2nd scanf where the user is giving the input as choosing the operator, it is not taking the input there.

// making a calculator
#include<stdio.h>
int main()
{
    int a,b;
    int ans;
    char c;

    printf("Enter your first number: \n");
    scanf("%d", &a);
    printf("Enter the operator '+','-','*','/': \n");
    scanf("%c", &c); //isn't taking the input here
    printf("Enter your second number: \n");
    scanf("%d", &b);
    if (c == '+')
    {
        ans = a+b;
        printf("Your answer is: %d",ans);
    }
    else if (c == '-')
    {
        ans = a-b;
        printf("Your answer is: %d", ans);
    }
    else if (c == '*')
    {
        ans = a*b;
        printf("Your answer is: %d", ans);
    }
    else if (c == '/')
    {
        ans = a/b;
        printf("Your answer is: %d", ans);
    }
    else
    {
        printf("Invalid input");
    }

    return 0;
}

all is okay but the the input where the user will put the operator isn't taking the input.

H.S.
  • 11,654
  • 2
  • 15
  • 32
ario
  • 15
  • 3
  • `scanf("%c", &c);` -> `scanf(" %c", &c);` i.e. add a space before `%c`. – H.S. Aug 19 '22 at 09:42
  • Don't use `scanf( )` much, but you could try `scanf( "%d%c%d", &a, &c, &b );` and see how you go... (That is, get all three pieces in a single operation...) – Fe2O3 Aug 19 '22 at 09:43
  • 1
    @Fe2O3 Likely better as `"%d %c%d"`. (Add space) – chux - Reinstate Monica Aug 19 '22 at 09:52
  • @chux-ReinstateMonica Closed before I could post trivial prototype... Put it into a loop so I used `" %d %c %d"`to also toss away the '\n' for the subsequent rounds... Worked when input was "45+50" and " 45 + 50"... Nice... :-) – Fe2O3 Aug 19 '22 at 10:00
  • 1
    @Fe2O3 Note the spaces before `"%d"` are not necessary, yet cause no harm either. – chux - Reinstate Monica Aug 19 '22 at 10:02

1 Answers1

1

In your code

printf("Enter your first number: \n"); scanf("%d", &a); 
printf("Enter the operator '+','-','*','/': \n");
scanf("%c", &c); 
printf("Enter your second number: \n"); 
scanf("%d", &b);

When you are done entering input into the first scanf() call, the input has a \n at the end. scanf() only reads characters that match the format specifier (%d in your first call), characters that do not match the format specific cause scanf() to stop scanning and will cause it to leave invalid characters in the stdin buffer.

In your case when you enter a int it is ended with a \n (newline character). This does not match the %d format specifier and is left in the stdin buffer. This will then cause the next scanf() call to read the newline character and look like it has just skipped a call.

Solution:

scanf(" %c", &c); 

Note:

scanf() is a quick and dirty input function, you should consider learning how to use something more reliable such as fgets().

programmer
  • 669
  • 3
  • 11