Basic calculator problem

how can we check that the input operator is + - etc
i have tried it with (+) and " " without anything it always gives error

@Learning_bunny
Treat it like any other character
char ch;
cin >> ch;
if( ch == ‘+’ ) {
--
}
else if( ch == ‘-’ ) {
--
}

instead of if statement can we use switch statement in it as it would be a bit easy to write i mean we dont have to write ch== so many times

@Learning_bunny
Ofcourse you can switch here. It’s completely your choice.

but when i am using switch case it is giving errors in handling operators like '+ ’ cant be converted into string , operator placed wrong like that

@Learning_bunny
There shouldn’t be an issue like that since we are comparing them as a character.
char ch;
cin >> ch;
switch(ch) {
case ‘+’ : cout << “Add”; break;
case ‘-’ : cout << “Subtract” ; break;
}

Code like this should work just fine.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

i have updated the code like https://ide.codingblocks.com/s/161539 when i am usiing while or for statement for creating infinite loop, compiler is not entering inside of the loop and output is nothing,when i am using it without loop then it is working fine but works only one time

Hey @Learning_bunny
You’ve to input ch inside your while loop, because you’ve to input ch every time again for the next operation, also it’d be better if the case ‘x’ and ‘X’ are included inside the switch itself, and a default case included for anything invalid, it’ll automatically switch to default case if it’s anything other than the operators or x/X,
based on this, your updated code, which should work fine is:

#include
#include<stdlib.h>
using namespace std;
int main() {
char ch;
int a,b;

while(1){
cin>>ch;
switch(ch){
case ‘+’:cin>>a>>b;
cout<<a+b << " ";
break;
case ‘-’:cin>>a>>b;
cout<<a-b << " ";
break;
case '’:cin>>a>>b;
cout<<a
b << " ";
break;
case ‘/’:cin>>a>>b;
cout<<a/b << " ";
break;
case ‘%’:cin>>a>>b;
cout<<a%b << " ";
break;
case ‘x’: exit(0);
break;
case ‘X’ :exit(0);
break;
default: cout << “invalid, try again”;
break;
}
//if(ch==‘x’ || ch==‘X’){
// exit(0);
//}
/* else{
cout<<“Invalid operation. Try again.”;
continue;
}*/
}
return 0;
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.