I normally don't create codes for myself, but today (or tonight, depending on your time zone) I created a simple calculator code which lets you enter multiple numbers, not just two items. This was a very ambitious idea, and so I got to work and then I tested it, and when I inserted my two numbers and my operator, it went back to the very first input (fyi, its the "please insert a number" prompt) and asked me again to insert a number, instead of checking my operator like I expected it to work.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int ans=0, num=0, secnum=0;
char oper, option;
bool statcheck = false;
while(!statcheck) {
cout<<"Please insert a number."<<endl;
cin>>num;
cout<<"Please insert another number."<<endl;
cin>>secnum;
cout<<"Select the operator you would like to use."<<endl;
cin>>oper;
switch(oper) {
case '+':
ans += num, secnum;
break;
case '-':
ans -= num, secnum;
break;
case '*':
ans *= num, secnum;
break;
case '/':
ans /= num, secnum;
break;
case '%':
ans %= num, secnum;
break;
default:
cout<<"Error."<<endl;
break;
}
goto anotherone;
cout<<"Would you like to add another number to the equation? (Y for yes, any other number for no)"<<endl;
cin>>option;
toupper(option);
if (option == 'Y') {
goto there;
secnum=0;
cout<<"What number would you like to add to the equation?"<<endl;
cin>>secnum;
cout<<"Select the operator you want to use."<<endl;
cin>>oper;
switch(oper) {
case '+':
ans += secnum;
break;
case '-':
ans -= secnum;
break;
case '*':
ans *= secnum;
break;
case '/':
ans /= secnum;
break;
case '%':
ans %= secnum;
break;
default:
cout<<"Error."<<endl;
there:;
break;
}
anotherone:;
}
else {
cout<<ans;
statcheck = true;
}
}
}
This seems to be the issue of the goto functions that I used in the code, as when I remove them, it works just fine, minus the ability to trap the user from inserting a random input in the "if (option == y)" condition.
I was expecting it to execute perfectly: it would ask for two numbers, the operator, ask if they wanted to add another number into the equation or not, and then it would give the answer. But of course, as an amateur at C++ and coding in general, once I got this unexpected and weird error, my mind was twisted (mainly because I'm very bad at debugging things, to be honest).