Reputation: 11
I am trying to get this portion of my C++ program to work so that the program reruns itself when 'y' is entered. When 'n' is entered, "Press any key to continue" needs to pop up.
What I have tried:
int main() {
char again;
if (again == 'y'){
// Asks user if they want to play again
cout << "Would you like to play again? (y/n):";
cin >> again;
} else if (again == 'n'){
cout << "Press any key to continue." << endl;
cin.ignore(1);
Output should look like this when 'n' is entered: Would you like to play again? n Press any key to continue . . .
output for 'y' should restart entire program
Upvotes: 0
Views: 5501
Reputation: 16338
Just can use a do-while
loop:
int main() {
char again;
do{
//code for the game goes here
// Asks user if they want to play again
cout << "Would you like to play again? (y/n):";
cin >> again;
}while(again=='y');
cout << "Press any key to continue." << endl;
cin.ignore(1);
}
This runs the game code over and over again until again
is not 'y'
.
Upvotes: 1
Reputation: 122133
Just in case you were planning to do this: You are not allowed to call main
yourself in C++.
However, that does not stop you from putting everything you have in main
into a function and call that inside a loop:
void my_program();
int main() {
char again;
do {
my_program();
// Asks user if they want to play again
cout << "Would you like to play again? (y/n):";
cin >> again;
} while (again == 'y');
}
PS: One problem in your code is that you are using the value of again
uninitialized.
Upvotes: 1