I am working on a basic calculator using a switch operator. Whenever an incorrect symbol/number is inserted, it's supposed to spit out an error and send the user to the beginning. Unfortunately, when this happens, it triggers an infinite loop. I was attempting to use label and goto, is there a better way to do this with the switch operator? The code works fine when you use the correct inputs, the infinite loop happens when you insert anything that is unexpected to the code.
int main(){
double var1; // established var1
double var2; // established var2
char symbol; // established symbol
cout << "Welcome to Cole's calculator program. This program can perform basic multiplcation, division, addition, and subtraction." << endl;
label:
cout << "Please enter your first number." << endl;
cin >> var1; // first input
cout << "Please enter your second number." << endl;
cin >> var2; // second input
cout << "Please enter your symbol. + for addition, - for subtraction, * for multiplication, and / for division." << endl;
cin >> symbol; // final input, non numberical
cout << endl;
switch(symbol) // a large if/else statement, inputs from symbol can only be what i include
{
case '+': // what to do when symbol = +
cout << var1 << " + " << var2 << " = " << var1+var2 << endl;
break; // end of this case
case '-': // what to do when symbol = -
cout << var1 << " - " << var2 << " = " << var1-var2 << endl;
break; // end of this case
case '*': // what to do when symbol = *
cout << var1 << " * " << var2 << " = " << var1*var2 << endl;
break; // end of this case
case '/': // what to do when symbol = /
if(var2 == 0){ // if second input is 0, spit out an error.
cout << "Error! Divide by 0" << endl;
}
else // if the second input is any other number
{
cout << var1 << " / " << var2 << " = " << var1/var2 << endl;
}
break; // end of this case
default: // if none of the cases are correct, or if any of the numberical variables are non-numberical
cout << "Error! Symbol is incorrect." << endl;
goto label;
break; // end of this case
}
return 0; // end of program
}