简体   繁体   English

如何显示错误消息,然后重新显示打油诗?

[英]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".通过这种方式,您可以更轻松地添加替代答案以退出while循环,例如“退出”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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