简体   繁体   中英

How do I display an error message, then redisplay the limerick?

Part of a program I am writing contains a function, in which the user guesses a word. If the word is correct, the function goes fine. If the word is incorrect, I do not know how to display something like "that's wrong try again", then redisplay the limerick.

Here is the function:

void guessLimerick()
{
    cout << "\nTime for a limerick guessing game!\nRead the following limerick, and type what you think the final word is,\nin all lowercase letters, followed by a period.\n\n";

    string final_word;
    do
    {
    cout << "\nIn pizza tech, changes abound.\nThe progress they serve is profound.\nI'd say it's a miracle to make the box spherical,\na box that is totally ";
    cin >> final_word;
    }
    while (final_word != "round.");

    if (final_word == "round.")
        cout << "\nThat's right!\nHave a great day!\n";
}

Thanks!

You can write your loop condition like this:

do
{
    cout << "\nIn pizza tech, changes abound.\nThe progress they serve is profound.\nI'd say it's a miracle to make the box spherical,\na box that is totally ";
    cin >> final_word;
} while (final_word != "round." && cout << "try again\n");

I would rewrite it in this more expanded way, I think compressing code in few lines decreases readability:

bool correct = false;
while (not correct)
{
    std::cout << "...";

    std::string finalWord;
    std::cin >> finalWord;

    bool correct = finalWord == "round";    
    if (not correct)
    {
        std::cout << "Try again\n";
    }
}

This way you can add more easily an alternative answer to go out of the while loop, like "quit".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM