Switch

Hi,

I do not want the user to be prompted to key in the first number and second number when the user keys in other than 1-5. It should show "Invalid choice" instead, when the user keys in other than 1-5.

How do I go about doing it?

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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;

int main()
{
	int Choice = 6;
	float firstNumber = 0;
	float secondNumber = 0; 
	float Result = 0.0;
	
	while (Choice != 5)
	{
		cout << "Simple Calculator" << endl;
		cout << "1: Addition" << endl;
		cout << "2: Subtraction" << endl;
		cout << "3: Multiplication" << endl;
		cout << "4: Division" << endl;
		cout << "5: Quit" << endl << endl;
		cout << "Please enter your choice: ";
		cin >> Choice;
	
			if (Choice != 5)
			{
				cout << "\nPlease enter the first number : ";
				cin >> firstNumber;
				cout << "Please enter the second number : ";
				cin >> secondNumber;
			}
		
			switch (Choice)
			{
				case 1 : Result = firstNumber + secondNumber;
				cout << "\nThe result is: " << Result << "\n\n";
				break;

				case 2 : Result = firstNumber - secondNumber;
				cout << "\nThe result is: " << Result << "\n\n";
				break;
		
				case 3 : Result = firstNumber * secondNumber;
				cout << "\nThe result is: " << Result << "\n\n";
				break;

				case 4 : Result = firstNumber / secondNumber;
				cout << "\nThe result is: " << Result << "\n\n";
				break;

				case 5 : cout << "\nEnd of Calculation";
				break;

				default : cout << "\nInvalid choice\n\n";
				break;
			}
		}

	cin.ignore();
	cin.ignore();

	return 0;
}
change line 22: if (Choice >= 1 && Choice <= 4)
Thank you!
Topic archived. No new replies allowed.