Search code examples
c++operatorscalculator

How to choose an operator when making a simple calculator in C++?


I'm making a simple calculator in C++, but I'm having trouble choosing an operator, I wonder who can help me? I'm using this code:

include <iostream>
using namespace std;
int main()
{
string operation = "";
cout << "enter operation:";
if(operation = "/"){
 int x;
 cin >> x;
 int y;
 cin >> y;
 int sum = x / y;
 }
 if(operation = "+"){
 int x;
 cin >> x;
 int y;
 cin >> y;
 int sum = x + y;
 }
 if(operation = "*"){
 int x;
 cin >> x;
 int y;
 cin >> y;
 int sum = x * y;
 }
 if(operation = "-"){
   int x;
   cin >> x;
   int y;
   cin >> y;
   int sum = x - y;
     }
   }

I dont know more programming. Who can help me?


Solution

  • I think you're missing a line to read in the operation the user enters. After the line cout << "enter operation:";, you probably need cin >> operation.

    A couple of other code improvements worth doing:

    • consider moving setting X and y outside the if statements, as you repeat the same code 4 times
    • consider using a switch statement rather than 4 if statements, as currently it will perform all 4 checks every time
    • as others have said, use == rather than =