gpt4 book ai didi

c++ - 如果输入错误,我的程序如何停止复制

转载 作者:行者123 更新时间:2023-12-01 14:53:06 24 4
gpt4 key购买 nike

我的程序将重复输出:“您目前位于5楼的2楼
码的总和为:7,码的乘积为:12
在他捕获你之前,再试一次!”
根据添加了多少个错误字符,我该如何解决?我已经插入了cin.clear和cin.ignore,但是它将重复上面的部分。

也就是说,如果我输入wasds,它将重复5倍。任何其他笔记也表示赞赏。

    #include <iostream>
#include <ctime>
using namespace std;

int PlayerLevel = 0;
int MaxLevel = 5;

bool GamePlay ()
{

srand(time(NULL));

int PlayerGuessA, PlayerGuessB, PlayerGuessC;

int CodeA = rand() % PlayerLevel + PlayerLevel;
int CodeB = rand() % PlayerLevel + PlayerLevel;
int CodeC = rand() % PlayerLevel + PlayerLevel;

int SumofCodes = CodeA + CodeB + CodeC;
int ProductofCodes = CodeA * CodeB * CodeC;

cout << "You are currently on the " << PlayerLevel << " floor out of 5" << endl;
cout << "The sum of the codes is: " << SumofCodes << " and the product of the codes is: " << ProductofCodes << endl;

cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;



int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;

if (PlayerProduct == ProductofCodes && SumofCodes == PlayerSum) {
cout << "Great Job you got this!!!\n" << endl;
++PlayerLevel;
return true;
}
else
{
cout << "Try again before he catches onto you!\n" << endl;
return false;
}

}


int GameStart()
{
string Introduction = "Welcome to your worst nightmare. You are trapped in a murderer's house. You are on the 5th floor and need to get to the first floor to escape.\n";
string Instructions = "He has each door locked behind a security system that requires a 3 number code to disarm it.\nEnter the codes and move foward. Each level will the code will be harder to figure out.\n";
string PlayerStart;

cout << Introduction << endl;
cout << Instructions << endl;
cout << "Would you like to escape? Yes or No" << endl;

cin >> PlayerStart;

if (!(PlayerStart != "Yes" && PlayerStart != "yes")) {
++PlayerLevel;
}
return 0;
}



int main ()
{

if (PlayerLevel == 0) {
GameStart();
}
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
cin.clear ();
cin.ignore();
}

cout << "You Made it out! Now run before he finds out!" << endl;
return 0;

}

最佳答案

当输入的类型与提取到的变量的类型不匹配时,cin将设置失败位。一旦发生这种情况,所有后续读取都会失败,直到重置流为止。令人讨厌的字符仍留在缓冲区中,因此也需要清除。
您对cin.clear()cin.ignore()的使用意味着将重置故障位,但是仅删除一个有问题的字符(默认情况下cin.ignore()忽略一个字符)。这就是为什么您看到输出对x个错误字符重复了x次的原因。

您可以执行以下操作:

while (PlayerLevel <= MaxLevel) 
{
bool bLevelComplete = GamePlay();
if (cin.fail())
{
//Input extraction failed, need to reset stream and clear buffer until newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');

}
}

关于c++ - 如果输入错误,我的程序如何停止复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61036479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com