#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <string>
#include <iomanip>
usingnamespace std;
int main ()
{
srand(time(NULL));
//Try to declare variables at beginning and then just edit them throughout the program.
bool run = true;//this will handle the loop
int num1;
int num2;
int sum, answer;
while (run == true)//loop will run while run is true
{
cout << "A Addition" << endl;
cout << "S Subtraction" << endl;
cout << "Q Quit" << endl;
cout << "Please enter your choice: ";
char choice;
cin >> choice;
switch(choice) //only need one switch(choice)
{
case'A':
case'a':
num1 = rand() % 100 + 1;
num2 = rand() % 100 + 1;
cout << num1 << endl;
cout << num2 << endl;
cout << " -----" << endl;
int answer;
cin >> answer;
cin.ignore(100, 10);
sum = num1 + num2;
if (answer == sum)
cout << "Congratulations, you got the right answer!" << endl;
else
{
cout << endl;
cout << "Sorry, that was wrong :(. Correct solution is" << endl;
cout << num1 << endl;
cout << num2 << endl;
cout << " -----" << endl;
cout << sum << endl;
}
cout << endl;
break; // always add breaks at end
case'S':
case's':
num1 = rand() % 100 + 1;
num2 = rand() % 100 + 1;
cout << num1 << endl;
cout << num2 << endl;
cout << " -----" << endl;
cin >> answer;
cin.ignore(100, 10);
sum = num1 - num2;
if (answer == sum)
cout << "Congratulations, you got the right answer!" << endl;
else
{
cout << endl;
cout << "Sorry, that was wrong :(. Correct solution is" << endl;
cout << num1 << endl;
cout << num2 << endl;
cout << " -----" << endl;
cout << sum << endl;
}
cout << endl;
break;
case'Q':
case'q':
run = false; //will make run false which will end the loop
break;
default: // this will make it so if they enter something that is not a A s S q Q then it will yell at them and keep the loop going
cout << "Please reread and reenter answer!" << endl;
break;
}
}
return 0;//always add return o; to end program
}
Try to declare variables at beginning and then just edit them throughout the program.
Bad. Declare variables where you need them. You'll also want to use getline rather than cin>>, otherwise you'll leave unconsumed input if the user happens to enter more than one character.
during a switch case statement declaring the variables during the case gives an error of
initialization of 'variable' is skipped by case label
that is why i said to declare before. I was talking about this program in particular in larger projects and others not being a switch case yes it is smarter to declare as you need.
and i was using run==true to show that the variable must be initialized to true i don't know how much programming this person has had and i thought it would make it easier to follow for them
and he/she has protected against extra characters using cin.ignore() so getline() is not necessary