Need help with basic calculator code

So the code I have here works as expected, but I'm trying to figure out a way to store the result of each if statement into a variable. My reasoning for this is because i want it to work like an actual calculator where the result of one input can be used for the next input. i.e. 2+4 = 6+2 = 8 etc. I'm curious as to what would be the best way to approach this.

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
#include <iostream>
#include <string>


int main()
{
	int num1;
	int num2;
	std::string myOperator;

	std::cout << "Please enter a number." << std::endl;
	std::cin >> num1;
	std::cout << "Please enter an operator, add or +, sub or , div or /, mul or *." << std::endl;
	std::cin >> myOperator;
	std::cout << "Please enter a number." << std::endl;
	std::cin >> num2;

	
	

		if ((myOperator == "add") || (myOperator == "+"))
		{
			std::cout << num1 + num2 << std::endl;
		}
		else if ((myOperator == "sub") || (myOperator == "-"))
		{
			std::cout << num1 - num2 << std::endl;
		}
		else if ((myOperator == "div") || (myOperator == "/"))
		{
			std::cout << num1 / num2 << std::endl;
		}
		else if ((myOperator == "mul") || (myOperator == "*"))
		{
			std::cout << num1 * num2 << std::endl;
		}


	return 0;
}
Hello BmoreCoding,

Welcome to the forum.

To do what you want you basically have to rewrite the program.

In the if/else of statements you will need to add something like: result = num1 + num2 The I would write the "cout" statement something like: std::cout << num1 << " + " << num2 << " = " << result << std::endl.

If you know about the switch/case I would consider using this over the if/else if statements. Although there is nothing wrong with the if/else if statements.

Most of the program needs to be in a do/while loop so that it will work more than once.

You will have to decide if the program will always use the "result" for the second and after calculations or if you will allow the user to choose two new numbers or use the "result" and a new number.

Hope that helps,

Andy
Topic archived. No new replies allowed.