使用按Enter键继续随机数字猜测 - 首次尝试跳过输入

时间:2018-03-18 06:18:20

标签: c++

首次运行时,它会跳过按下输入输入。在此之后它工作正常 它应该执行以下操作:

  • 要求您选择一个号码(工作)
  • 猜数字(工作)
  • 要求你按回车继续(不工作跳过第一次输入进入工作正常第二次尝试)。

我的代码:

while (counter != guess)
{
    int randnum = rand() % (max - min + 1) + min;
    counter = randnum;
    counter2++;

    if (counter == guess)
    {
        cout << "The computer has guessed your number to be " << guess << 
                ". The computer got this answer in " << counter2 << " tries." << 
                endl;

    }
    else if (counter > guess)
    {
        cout << "The computer has guessed your number to be " << counter << 
                ". This answer is greater than your input. " << endl;
        max = counter - 1;
    }
    else if (counter < guess)
    {
        cout << "The computer has guessed your number to be " << counter << 
                ". This answer is less than your input. " << endl;
        min = counter + 1;
    }

    cout << "Press Enter to Continue" << endl;
    cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}

1 个答案:

答案 0 :(得分:1)

问题是,当你执行std::cin时,你将把任何角色带到下一个空格。当您输入计算机试图猜测的数字时,您实际上是在放入50\n而不是50。这意味着cin取50,但保留\n,由cin.ignore()选取。当程序到达cin.ignore()时,因为流中有一些东西,首先处理,然后从用户那里获得输入。由于\n已经在流中,因此首先处理并满足该行代码,因此它继续进行。