当我运行此选项并在选择我的号码作为播放器后,计算机将返回两个输出(而不是一个......)。我不明白为什么,你能帮我解释一下为什么会这样吗?
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int random(int a, int b)
{
int num = a + rand() % (b + 1 - a);
return num;
}
int main()
{
srand(time(NULL));
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
int min = 1;
int max = 100;
int comp;
string player;
while(1) {
comp = random(min, max);
cout << "Computer: " << comp << endl; // why does this get called twice??
getline(cin, player);
if (player == "too high") {
max = comp - 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "too low") {
min = comp + 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "correct") {
cout << "Computer found the number..." << endl;
break;
}
}
}
答案 0 :(得分:1)
这是因为您正在使用>>
和getline
混合输入。 getline
读到下一个换行符,>>
没有。输入您的号码后,仍然会留下换行符,您已输入该号码,但尚未阅读。您第一次拨打留下换行符的getline
时会被读取,并且该程序不会暂停。只有在您第二次拨打getline
时,您的程序才会暂停并等待您输入内容。
解决问题的简单方法是
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
// flush pending newline
string dummy;
getline(cin, dummy);