This question already has an answer here:
I'm trying to finish up my "Math addition quiz" program but I have an issue with the output. Here's my code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string choice;
do
{
cout << "Please type something: ";
getline(cin, choice);
while (choice != "1" && choice != "5") //validation against string
{
cout << "Incorrect choice! Please input a valid number: >_";
getline(cin, choice);
}
unsigned seed = time(0);
srand(seed);
if (choice == "1")
{
double num1, num2,
result, answer;
num1 = rand() % 1000;
num2 = rand() % 1000;
result = num1 + num2;
cout << "\n " << num1 << " + " << num2 << " = ";
cin >> answer;
if (answer == result)
cout << "\nCongratulation! You got it right!\n\n";
else
cout << "\nNope! The correct answer is " << result << "\n\n";
}
else if (choice == "5")
cout << "\nThank you for using the program!\n";
} while (choice == "1");
return 0;
}
After I press 1, and do the math (doesn't matter if I did it correctly or not), the second time output ends up as follow:
Please type something: Incorrect choice! Please input a valid number: >_
Please help me fix this. My guess is that 'getline' reads something in the nested if, I just don't know which one.
Aucun commentaire:
Enregistrer un commentaire