Looping Calculator help

Hi folks!
I'm having trouble with the last segment of this assignment. It's pretty much done otherwise. The idea is that if I enter an operator of say '@' or '$,' I can still continue to enter the numbers, but I get a prompt telling me it's bad and it will loop back to start like normal. Here's the code first:

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
#include <iostream>
using namespace std;

int calculate (char op, double n1, double n2, double & res)
{
    cout << "Enter the first number: " << endl;
    cin >> n1;

    cout << "Enter the second number: " << endl;
    cin >> n2;

	switch (op)
	{
		case '+':
			res = n1 + n2;
			break;

		case '-':
			res = n1 - n2;
			break;

		case '*':
			res = n1 * n2;
			break;

		case '/':
			res = n1 / n2;
			break;

		default:
			cout << "ERROR: This operation is invalid. Please try again. \n" << endl;
			break;
	}
    return res;
}

int main()
{
    double n1;
    double n2;
    double res;
    char op;

    cout << "Enter an operation (+, -, *, or /): " << endl;
    cin >> op;
    while (op == '+' || op == '-' || op == '*' || op == '/')
    {
    calculate(op, n1, n2, res);

    cout << "\nThe result is: " << res << endl;

    cout << "\nEnter an operation (+, -, *, or /): " << endl;
    cin >> op;
    }
}



When it does +, -, /, and *, it loops as it should. My problem is that on the default line, nothing shows and the program ends. I'm certain the error is that my while code is lacking. Here's my train of thought:

For a while, I tried using "if / else if" first and thought if I flipped the while code (making == into !=, and || into &&) in the last else if line, but that did nothing. I decided to make things simpler and use a switch instead. I removed the while code and it worked fine. That's where I drew my conclusion that the while code is where I need to work on.

What do I need to add/change to continue this loop? Or is there some other solution I'm not seeing? I checked the operand page here on the site, but I couldn't find anything.
Last edited on
Before I forget, I wanted to ask about the "&" in "double & res." I wasn't properly taught this and just sort of copied through the motions. I know it works, but I don't understand the point of & too well. I was hoping someone could break it down so I'd understand why I use this in the future.

Thank you!
Never mind, I figured it out. Had to change the while code to "op != 'x'". Kind of against the instructions, but considering the end result, I doubt the instructor will care.

Sorry to trouble everyone.
Topic archived. No new replies allowed.