【问题标题】:C++ pause function not seeming to work within do-while loopC++ 暂停函数似乎在 do-while 循环中不起作用
【发布时间】:2014-07-04 06:20:33
【问题描述】:

我正在用 c++ 编写刽子手,它也接受来自用户的命令(以便他们可以看到线索并退出游戏)。

我目前正在执行命令,但似乎无法使其工作。我被困在一个帮助命令上,该命令使用pause() 函数让用户阅读文本。

暂停功能似乎不起作用,即使它在程序的早期工作过。

到目前为止的代码

这里是代码:HelloWorld.cpp

void pause( string msg = "Press enter to continue..." ){
    cout << msg;
    cin.ignore();
}

// game loop.
do {
    correctLetters = 0;

    nl();
    showLives(lives);
    nl(5);
    showWordGuessed(wordGuessed);
    nl(1);
    cout << "Guess a letter (type /help to see commands): ";
    cin >> guess;

    if (guess.size() == 1){
        for (int i = 0;i < 5;i++){
            if (word[i] == guess) wordGuessed[i] =  word[i];
        }
    } else if (guess[0] == '/'){
        if (guess == "/ans"){

        } else if (guess == "/clue"){

        } else if (guess == "/help"){
            nl();
            cout << "Typing /ans will show you the answer and quit the game.\n";
            cout << "Typing /clue will show you one unknown letter.\n";
            cout << "Typing /guess will allow you to guess the entire word.\n";
            cout << "Typing /hangman will quit the game.\n";
            cout << "Typing /help will show you this help message.\n\n";
            pause("Press enter to continue playing...");
        } else if (guess == "/guess"){

        } else if (guess == "/hangman"){
            return 0;
        } else {

        }
    } else {
        nl();

    }

    for (int i = 0;i < 5;i++){
        if (wordGuessed[i] ==  word[i]) correctLetters++;
    }

    win = ((correctLetters == 5) ? win = true : win = false);

} while (!win);

cout << "you win";

【问题讨论】:

  • edit你的问题有一个更有意义的标题(主题)。 “为什么我的 C++ 程序不起作用?”绝对没有信息,对于在搜索结果中找到它的未来读者肯定不会有用。谢谢。

标签: c++ function while-loop do-while


【解决方案1】:

您的暂停功能并没有完全按照您的想法进行。

让我们想象一下从输入流中读取一些数据,如下所示:

int i;
std::cin >> i;

用户输入一个数字,然后点击返回。 operator&gt;&gt; 将从cin 中提取字符,直到找到无法转换为int 的字符,然后将其保留在那里。在普通用户输入的情况下,留在流上的字符是换行符 (\n)。

当您调用pause 函数时,您尝试这样做:

std::cin.ignore()

这将忽略输入流中的一个字符。只有上次有人输入数据时,流中有一个流浪的\n!所以pause 立即返回。

您需要在使用后采取措施清理您的输入流,也许每次使用 std::cin &gt;&gt; whatever 后都这样做。

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

这会将最后一个有效输入字符之后的所有内容删除到最后一个换行符。在那之后,您的暂停功能可能会更好地工作。

或者,您可以使用getline,而不是使用&gt;&gt;,它旨在处理以换行符结尾的文本字符串。

std::string stuff;
std::getline(std::cin, stuff);

if (stuff.length() > 1)
    std::cout << "Easy, tiger.\n";

getline 会为您删除尾随的\n,这也将有助于您的pause 函数更好地工作。

【讨论】:

  • 哪个“这个”?我提到了几件事!但我建议在您当前使用cin &gt;&gt; 的所有地方使用getline 代码。这应该是一个简单的改变,你可以看看它是否解决了你的问题。
猜你喜欢
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多