同时执行循环一次显示2条提示,请回复

问题描述

我是编程和尝试程序的新手,您需要猜测视频游戏角色的名称,如果用尽了所有猜测,将会丢失3个猜测。我在这里使用了一个do-while循环,所以我可以一次又一次地执行...这里的问题是,每次循环再次启动时,它会显示两次提示,即使每次猜测应该是一次提示,但也会显示一次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;
}

解决方法

编辑: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