plz help calculator problem

Hi am writing code for the calculator for add subtract divide and multiply.

on three of the lines it says expected expression and Idk why. can someone plz help? I woulld really appreciate it. Thanks so much in advance!! error is displayed on lines 15, 18 , and 21

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
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    string n1;
    string n2;
    string response;
    string action;
cout<< "Hello, enter +, -,/ or *.";
    cin>>n1>>action>>n2;
   if(action == "+")
       response = n1 + n2;
     cout<< "answer="<<response;
    else if(action == "*")
        response = n1 * n2;
     cout<< "answer="<<response;
    else if(action == "-")
        response == n1 - n2;
    cout<< "answer="<<response;
    else if(action == "/")
        response == n1 / n2;
    cout<< "answer="<<response;
    return 0;



 }
response == n1 / n2;

You aren't using the correct operator to assign the value to response. You should use the assignment operator for this. You are also using a string, so arithmetic operators won't work (except '+' because it has been overloaded). You'll have to use two integers and a character if you want to make a calculator like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main(void) {
    char op;
    float num1, num2, ans;
    std::cout << "Calculation: ";
    std::cin >> num1 >> op >> num2;
    switch(op) {
    	case('+'):
    		ans = num1+num2;
    		break;
    	case('-'):
    		ans = num1-num2;
    		break;
    	case('/'):
    		ans = num1/num2;
    		break;
     	case('*'):
    		ans = num1*num2;
    		break;
    }
    std::cout << num1 << ' ' << op << ' ' << num2 << " = " << ans;
    return 0;
}
Last edited on
Your error comes from the lack of braces. You need braces if your condition has more than one statement associated with it. So, line 13 is part of the if condition, but line 14 isn't, and happens no matter what. Line 15 is else if, which can only happen after an if, so your compiler has issue.

So:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if(action == "+")
{
  response = n1 + n2;
  cout<< "answer="<<response;
}  
else if(action == "*")
{  
  response = n1 * n2;
  cout<< "answer="<<response;
}
else if(action == "-")
{
  response = n1 - n2;
  cout<< "answer="<<response;
}
else if(action == "/")
{
  response = n1 / n2;
  cout<< "answer="<<response;
}


But isn't this better anyway?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if(action == "+")
{
  response = n1 + n2;
}  
else if(action == "*")
{  
  response = n1 * n2;
}
else if(action == "-")
{
  response = n1 - n2;
}
else if(action == "/")
{
  response = n1 / n2;
}
cout<< "answer="<<response;


As xhtmlx says though, the whole thing isn't going to work like that.

~You also didn't make sure the denominator wasn't zero~
Last edited on
Topic archived. No new replies allowed.