C++ 使用按enter键继续随机猜测数值-第一次尝试时跳过输入
第一次运行时,它跳过按enter键输入。在这之后,它工作得很好 它应做到以下几点:C++ 使用按enter键继续随机猜测数值-第一次尝试时跳过输入,c++,C++,第一次运行时,它跳过按enter键输入。在这之后,它工作得很好 它应做到以下几点: 请您选择一个号码(工作) 猜测数字(工作) 要求您按enter键继续(不工作跳过enter的第一次输入,第二次尝试效果良好) 我的代码: while (counter != guess) { int randnum = rand() % (max - min + 1) + min; counter = randnum; counter2++; if (counter == g
- 请您选择一个号码(工作)
- 猜测数字(工作)
- 要求您按enter键继续(不工作跳过enter的第一次输入,第二次尝试效果良好)
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');
}
while(计数器!=猜测)
{
int randnum=rand()%(max-min+1)+min;
计数器=随机数;
计数器2++;
如果(计数器==猜测)
{
问题是,当你输入std::cin
时,你会把任何字符带到下一个空白处。当你输入一个计算机试图猜测的数字时,你实际上输入的是50\n
,而不是50
。这意味着cin
取50,但保留了拾取的\n
当程序到达cin.ignore()时,由cin.ignore()启动
,因为流中有一些东西是先处理的,然后从用户那里获得输入。因为\n
已经在流中,所以先处理它并满足该行代码,所以它继续前进。总是将示例代码精简为一行。