Why does this program output 2 x Enter First Letter at a wrong answer?

http://s24.postimg.org/tvtkybrhh/image.jpg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #include <stdio.h>
int main(void)
{
	int a, b;
	char ch;
	printf("Do you want to:\n");
	printf("Add, Subtract, Multiply or Divide?\n");
	do
	{
		printf("Enter first letter: ");
		ch = getchar();
	} while (ch != 'A' && ch != 'S' && ch != 'M' && ch != 'D');
	printf("\n");
	printf("Enter first number: ");
	scanf_s("%d", &a);
	printf("Enter second number: ");
	scanf_s("%d", &b);
	if (ch == 'A') printf("%d", a + b);
	else if (ch == 'S') printf("%d", a - b);
	else if (ch == 'M') printf("%d", a * b);
	else if (ch == 'D' && b != 0) printf("%d", a / b);
	return 0;
}
Last edited on
Ok,
Please quit using scanf--we use cout in C++. scanf is from C.
Thank you!
Your Program is picking up the newline character that gets sent when you press Enter. Instead of ch = getchar(); use scanf(" %c", &ch); the space before %c tells the compiler to ignore any whitespace characters. Alternatively you could use std::cin.
Last edited on
Topic archived. No new replies allowed.