首次运行时,它会跳过按下输入输入。在此之后它工作正常 它应该执行以下操作:
我的代码:
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');
}
答案 0 :(得分:1)
问题是,当你执行std::cin
时,你将把任何角色带到下一个空格。当您输入计算机试图猜测的数字时,您实际上是在放入50\n
而不是50
。这意味着cin
取50,但保留\n
,由cin.ignore()
选取。当程序到达cin.ignore()
时,因为流中有一些东西,首先处理,然后从用户那里获得输入。由于\n
已经在流中,因此首先处理并满足该行代码,因此它继续进行。