繁体   English   中英

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

[英]How do I my Program to stop Replicating if wrong input

我的程序会重复 output:“你目前在 2 楼,共 5 个代码的总和是: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 设置失败位。 一旦发生这种情况,所有后续读取都会失败,直到 stream 复位。 有问题的字符仍留在缓冲区中,因此也需要将其清除。
您对cin.clear()cin.ignore()的使用意味着失败位被重置,但只有一个违规字符被删除( cin.ignore()默认忽略一个字符)。 这就是为什么您看到 output 针对 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');

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM