cout done twice problem !!

Hello, I have a problem with my code,

My code is :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int choice, a, b;

	cout << "Simple calculator\nPlease enter two integers: ";
	cin >> a >> b;

	do {
		cout << "Now enter operation (+, -, *, /, %) or E to exit: ";
		choice = cin.get();
	switch ( choice )

	{
	case '+':
		cout << "The sum = " << a + b << endl << endl;
		break;
	case '-':
		cout << "The difference = " << a - b << endl << endl;
		break;
	case '/':
		cout << "The quotient = " << setprecision(2) << static_cast< double >( a ) / b << endl << endl;
		break;
	case '*':
		cout << "The product = " << a * b << endl << endl;
		break;
	case '%':
		cout << "The remainder = " << a % b << endl << endl;
		break;
	case 'E':
		cout << "You choose E ... BYE" << endl;
		break;
	case '\n':
	case '\t':
	case ' ' :
		break;
	default:
		cout << "Ops, Sorry, wrong choice, try again" << endl;
	}

	} while ( choice != 'E' );

return 0;
}


when I execute the program, it looks like:

Simple calculator
Please enter two integers: 9 2

Now enter operation (+, -, *, /, %) or E to exit: Now enter operation (+, -, *,
/, %) or E to exit:


All operations are perfect, except that it couts twice !!
Have any one noticed my mistake?
Thanks in advance.
When you use the insertion operators >> on line 10 to read into your variables, you are left with a '\n' from pressing enter. The first call to cin.get() reads the newline character and enters the switch the choice equal to '\n'.

You should probably ignore() any remaining input in cin before reading in the character with get().
Thank you for your quick assistance.
I need more explaining, what should I add to the code ? or what should I remove ?
I am sorry, I have only 1 week experience :P, so forgive me.

Update: I added cin.ignore('\n');
before choice = cin.get();

the twice problem disappeared, but new problem happened, no cout is gonna be happen in switch
I mean when I input + - / * % , nothing happens
Last edited on
All thanks to Zhuge, without him I will never get my full mark in that question
For those who want to know how:
I added this line : cin.ignore(1,'\n'); // Thanks to Zhuge
before the line : choice = cin.get();
Problem solved
Topic archived. No new replies allowed.