Do while循环一次显示2个提示,请回复
Do-while loop displays 2 prompt at a time, please reply
我是编程和尝试一个程序的新手。你需要猜测一个电子游戏角色的名字,只有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
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 这两个代码片段相似,但显示的结果不同
- 创建具有两个视口的Qt3D C++场景,其中显示适当的不同网格
- 更改高度贴图,使其在 4x4 网格上显示 16 个 hieghtmap
- 在 txt 文件中显示前两个数字的程序
- Windows 资源管理器中的图标在使用 resource.rc 时显示 2 个不同的图标
- 我的程序将 26 个字母转换为 ascII 没有显示正确答案
- 在数组中显示第一个元素用户输入
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 创建第二个应用窗口并显示它
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 使用 Splashkit 逐个显示多个C++图像
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 输出显示多个带整数的字符串值
- 当被一个输入分开时,有两个控制台输出同时显示
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 在 Qt 中显示多个图像缩略图
- 如何计算和显示C++中5个数字的平均值?
- C++ 快板第一个显示程序 - 平移旋转刻度
- Opencv中第一个显示图像的项目,错误.