Do while循环一次显示2个提示,请回复

Do-while loop displays 2 prompt at a time, please reply

本文关键字:2个 显示 提示 回复 一次 循环 while Do      更新时间:2024-09-21

我是编程和尝试一个程序的新手。你需要猜测一个电子游戏角色的名字,只有3个猜测,如果你的猜测用完了,你就会输。我在这里用了一个做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;
}

EDIT:stackoverflow.com/a/21567292/4465334是您的问题的一个很好的例子,解释了您遇到问题的原因,并解释了如何解决问题。我在下面提供了您代码的一个工作示例,以及有关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