提问者:小点点

Do-while循环一次显示2个提示,请回复“重复”


我是新的编程和尝试一个程序,你需要猜测一个视频游戏角色的名字,只有3个猜测,如果你用完猜测你将失去。我在这里用了一个do-while循环,这样我就可以一遍又一遍地做。。。这里的问题是,每次循环再次启动时,它会显示2次提示,即使它应该是1次提示,但它显示了2次提示。你能帮帮我吗?也许我的算法做错了,谢谢!

#include <iostream>

using namespace std;

int main()
{

    char rerun_option;

    do {
        string secretWord = "Arthur Morgan";
        string guess;
        int guessCount = 0;
        int guessLimit = 3;
        bool outofGuesses = false;

        while (secretWord != guess && !outofGuesses) {
            if (guessCount < guessLimit) {
                cout << "Enter video game character name guess: ";
                getline(cin, guess);
                guessCount++;
            }
            else {
                outofGuesses = true;
            }
        }
        if (outofGuesses) {
            cout << "You Lose!" << endl;
            outofGuesses = false;
        }
        else {
            cout << "You Win!" << endl;
        }

        cout << "Try Again?(Y/N) ";
        cin >> rerun_option;
    } while (rerun_option == 'Y' || rerun_option == 'y');

    return 0;
}

共1个答案

匿名用户

编辑:stackoverflow.com/a/21567292/4645334是您的问题的一个很好的例子,解释了您为什么会遇到它,并解释了您如何解决它。我在下面提供了您的代码的工作示例,以及指向有关cin.ignore()的使用和描述的更多信息的链接。

#include <iostream>

using namespace std;

int main()
{

    char rerun_option;

    do {
        string secretWord = "Arthur Morgan";
        string guess;
        int guessCount = 0;
        int guessLimit = 3;
        bool outofGuesses = false;

        while (secretWord != guess && !outofGuesses) {
            if (guessCount < guessLimit) {
                cout << "Enter video game character name guess: ";
                cin.ignore(); // <-- ADD THIS LINE RIGHT HERE
                getline(cin, guess);
                guessCount++;
            }
            else {
                outofGuesses = true;
            }
        }
        if (outofGuesses) {
            cout << "You Lose!" << endl;
            outofGuesses = false;
        }
        else {
            cout << "You Win!" << endl;
        }

        cout << "Try Again?(Y/N) ";
        cin >> rerun_option;
    } while (rerun_option == 'Y' || rerun_option == 'y');

    return 0;
}

https://www.tutorialspoint.com/what-is-the-use-of-cin-ignore-in-cplusplus