So I wrote these codes when I ran it and input the right answer, it works perfectly fine, but if I put the wrong answer and use the while loop to run the program again, it outcome will store the last input and does not let me input anymore.
I found out that you can add guess.clear();
to clear the memory which is stored in the variable "guess".
#include <iostream>
#include <string>
#include <inttypes.h>
using namespace std;
int main(){
int replay = 0;
int input = 0;
while(input == replay){
string celebrity = "Keeves Reeves";
string guess;
guess.clear();
cout << "Hint: He acted as John Wick." << endl;
cout << "Guess who's this celebrity is: ";
getline(cin, guess);
if(guess == celebrity){
cout << "Congratulations! You got it!\n" << endl;
input = 2;
} else if(guess != celebrity){
cout << "Whoops, that not the right answer..." << endl;
cout << "Do you want to try again? Enter '0' to replay or enter '1' to view the answer: ";
cin >> input;
if (input == 1){
cout << "The answer is " + celebrity + "." << endl;
input = 2;
}
}
}
cout << "Thank you for playing. The end." << endl;
system("pause");
return 0;
}
Outcome:
Hint: He acted as John Wick.
Guess who's this celebrity is: Michael
Whoops, that not the right answer...
Do you want to try again? Enter '0' to replay or enter '1' to view the answer: 0
Hint: He acted as John Wick.
Guess who's this celebrity is: Whoops, that not the right answer...
Do you want to try again? Enter '0' to replay or enter '1' to view the answer: