calculator using switch case statement is not working ,can anybody tell me why it is so.

#include<iostream>
using namespace std;
int main()
{
string calculation;
double a;
cin>>a;
char temp;
switch (calculation)
{
case "add":
temp ='+';
break;
case "subtract":
temp ='-';
break;
case "multiply":
temp ='*';
break;
case "divide":
temp = '/';
break;
}
double b;
cin>>b;

double result;
result =a temp b;
cout<<:<<result;
}
Because char cannot be a operator directly
In order to turn char into operator you would need either switch or if-else
1
2
3
string calculation;

switch (calculation)


in function 'int main()': 12:24: error: switch quantity not an integer

The switch is expecting an integer value, not a string. Calculation also has no value at the time the switch begins.
Also...I just realized calculation has no value...
You could switch on a char representing the operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    double a;
    std::cin >> a;
    char oper;
    std::cin >> oper;
    double b;
    std::cin >> b;
    
    switch (oper)
    {
        case '+':
            std::cout << a << " + " << b << " = " << a + b << "\n";
            break;
        // and so on
    }
3 + 5
3 + 5 = 8
Last edited on
Topic archived. No new replies allowed.