繁体   English   中英

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

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

我正在编写的程序的一部分包含一个函数,用户可以在其中猜测一个单词。 如果单词正确,则功能正常。 如果单词不正确,我不知道如何显示“那是错误的再试一次”之类的内容,然后重新显示打油诗。

这是函数:

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";
}

谢谢!

您可以像这样编写循环条件:

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");

我会以这种更扩展的方式重写它,我认为在几行中压缩代码会降低可读性:

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";
    }
}

通过这种方式,您可以更轻松地添加替代答案以退出while循环,例如“退出”。

暂无
暂无

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

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