Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用按enter键继续随机猜测数值-第一次尝试时跳过输入_C++ - Fatal编程技术网

C++ 使用按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键继续(不工作跳过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
已经在流中,所以先处理它并满足该行代码,所以它继续前进。

总是将示例代码精简为一行。