### Help improve this calculator

I'm an ultimate beginner of C++. How do i make this calculator restart without re-running it? I heard of loops, but I'm still not sure how to use those. also, are there any ways to make this calculator more simple? instead of adding many if statements?

 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 #include using namespace std; int a; int b; string symbol; int sum; int main() { cout << "Hello and thank you for using this Calculator! \n\n"; cout << "Enter a number(s) \n"; cin >> a; cout << " \n"; cout << "Now enter a symbol (+,-,*,%) \n"; cin >> symbol; cout << " \n"; cout << "Enter another number(s) \n"; cin >> b; cout << " \n"; if(symbol == "+"){ sum = a+b; cout << "The answer is "; cout << sum; }else if(symbol == "-"){ sum = a-b; cout << "The answer is "; cout << sum; }else if(symbol == "*"){ sum = a*b; cout << "The answer is "; cout << sum; }else if(symbol == "%"){ sum = a%b; cout << "The answer is "; cout << sum; } return 0; }
You can make it simpler by using switch statement, a char for the operation and just validate your input as you go

 123456789101112131415161718192021 int num1, num2, sum; char op; while (std::cin >> num1 >> op >> num2) { switch (op) { case '+': sum = num1 + num2; break; case '-': sum = num1 - num2; break; } // /, *, ... std::cout << sum << std::endl; }
Last edited on
Thanks, ill try that!
Topic archived. No new replies allowed.