Morrese Morrison
Morrese Morrison

Reputation: 5

How to repeat program if user says they want to play again?

I've created a program that asks for shoe size. If the shoe size is correct, the user will get a message that says, "You are correct would you like to try again?" They can either answer yes or no. If they select "no" the program will break and they will get another message that says, "Thanks for playing!"

Is there a way to basically force the program to break back into the while loop if the user enters yes as an answer instead of no?

#include <iostream>
#include <string>
using namespace std;

int main()
{

    int shoesize = 13;
    int input;
    string answer;

    while (input != shoesize) {
        cout << "Guess my shoe size!";
        cin >> input;

        if (input == shoesize) {
            cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
            cin >> answer;

            if (answer == "no") {
                cout << "Thank you for playing!";
            }
        }
    }
    return 0;
}

Upvotes: 0

Views: 1400

Answers (2)

Mike Robinson
Mike Robinson

Reputation: 8945

Easily the best way to write something that "repeats continuously until you want to quit" is to just do something like this:

while(true) {
  .. do something ..
  .. ask "do you want to quit" ..
  if (answer == "yes") {
    break;
  }
}

Programmers will instantly recognize the while(true){} "endless" loop, and look for the break statement which – as the name implies, "breaks out of" the innermost loop, ending the "endless" loop. One nice thing about this design is that you can use the break statement in more than one place within the loop as needed. (Within a function, you can also return.)

Upvotes: 1

thedudehimself
thedudehimself

Reputation: 67

How about this.

#include <iostream>
#include <string>
using namespace std;

int main()
{

    int shoesize = 13;
    string answer;
    int input = 0;

    while (input != shoesize && answer != "no") {
        cout << "Guess my shoe size!";
        cin >> input;

        if (input == shoesize) {
            cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
            cin >> answer;

            if (answer == "no") {
                cout << "Thank you for playing!";
                return 0;
            }
        }
    }
}

Upvotes: 0

Related Questions