#include <stdio.h>
int main() {
char operator;
int a,b;
printf("Enter 1st operands: ");
scanf("%d",&a);
printf("Enter 2nd operands: ");
scanf("%d",&b);
//here after taking the input of integers the code skips to default without
//taking the character input
printf("Enter an operator (+, -, *,/): ");
scanf("%c", &operator);
switch(operator)
{
case '+':
printf("%d+ %d = %d",a, b, a + b);
break;
case '-':
printf("%d- %d = %d",a, b, a - b);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
Asked
Active
Viewed 1,062 times
0

Jabberwocky
- 48,281
- 17
- 65
- 115

Alinoor Rahman
- 11
- 1
-
@xing: Please write answers in the answer section, where they can be more readily peer reviewed. – Bathsheba Feb 06 '17 at 15:02
-
Can you please elaborate? or give any descriptive links? I didn't properly understand the matter. tia – Alinoor Rahman Feb 06 '17 at 15:26
2 Answers
2
scanf("%c", &operator);
actually reads the newline character that remains on the input stream.
The remedy - scanf(" %c", &operator);
- note the space, is the idiomatic way of getting round this.

Bathsheba
- 231,907
- 34
- 361
- 483
-
Can you please elaborate? or give any descriptive links? I didn't properly understand the matter. tia – Alinoor Rahman Feb 06 '17 at 15:26
-
Get your favourite debugger out. Look at `operator` before the `switch` block. Bet you a quid it's 10, corresponding to what happens when you press your Return key on the keyboard. – Bathsheba Feb 06 '17 at 15:27
1
Write
scanf(" %c", &operator);
^^^^
Otherwise control characters will be stored in the object.
From the function description in the C Standard (7.21.6.2 The fscanf function)
5 A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

Vlad from Moscow
- 301,070
- 26
- 186
- 335
-
Can you please elaborate? or give any descriptive links? I didn't properly understand the matter. tia – Alinoor Rahman Feb 06 '17 at 15:26
-