Basic Calculator Problem Error

#include
using namespace std;

int main() {
char ch;
int n1, n2;
while(cin>>ch) {
switch(ch) {
case ‘+’: cin>>n1>>n2; cout<<n1+n2<<endl; break;
case ‘-’: cin>>n1>>n2; cout<<n1-n2<<endl;break;
case '’: cin>>n1>>n2; cout<<n1n2<<endl;break;
case ‘/’: cin>>n1>>n2; if(n2!=0) {cout<<n1/n2<<endl; }
break;
case ‘%’: cin>>n1>>n2; if(n2!=0) {cout<<n1%n2<<endl; }
break;
case ‘X’: exit(0);
case ‘x’: exit(0);
default: cout<<“Invalid operation. Try again.”;
}
}
return 0;
}

Where is the code lacking? There are 3 test cases that says ‘wrong-answer’. PLease suggest changes.

Hi Shivani, use a do-while loop for this question. Also check the constraints of the problem, you’ll need to use long long int.

Yes, made the changes but still, test cases 1, 2 and 4 are coming as wrong.

#include
using namespace std;

int main() {
char ch;
long long int n1, n2;
cin>>ch;
if(ch==‘X’ || ch==‘x’)
exit(0);
else {
do {
switch(ch) {
case ‘+’: cin>>n1>>n2; cout<<n1+n2<<endl; break;
case ‘-’: cin>>n1>>n2; cout<<n1-n2<<endl;break;
case '’: cin>>n1>>n2; cout<<n1n2<<endl;break;
case ‘/’: cin>>n1>>n2; if(n2!=0) {cout<<n1/n2<<endl; }
break;
case ‘%’: cin>>n1>>n2; if(n2!=0) {cout<<n1%n2<<endl; }
break;
default: cout<<“Invalid operation. Try again.”;
}
cin>>ch;
if(ch==‘X’ || ch==‘x’)
exit(0);
} while(ch!=‘X’ || ch!=‘x’);
}
return 0;
}

Hi Shivani, there is a little bug here. See what happens when you give an irrelevant input.
For example:
Input

+ 3 1
3 3 1
x

Your Output

4
Invalid operation. Try again.
Invalid operation. Try again.
Invalid operation. Try again.

Correct Output

4
Invalid operation. Try again.

"Invalid operation. Try again." is printing 3 times instead of 1 for 1 wrong testcase.

I am marking your doubt as Resolved for now. Re-open it if required