可能重复:
程序不等待 cin
我写了以下代码:
#include <iostream>
using namespace std;
void search(int pre, int a, int b, int x) {
char c;
cout << "Is the number " << ((x == 2) ? b : a) << endl;
c = cin.get(); ////// this does not block
if (c == 'y') return;
else {
cout << "Is the number " << ((x == 2) ? b : a) << " closer to your number than " << pre;
c = cin.get();
if (c == 'y') {
search(a, a, (a + b) / 2, 2);
} //c=='y'
else search(a, (a + b) / 2, b, 1);
}
}
int main() {
int N;
cout << "Enter N? ";
cin >> N;
search(N, 1, N, 1);
return 0;
}
如果您不理解逻辑,则无需担心,因为我的问题与此无关。
在搜索功能中,有两个 cin.get(),我需要用户输入一个字符。我的问题是程序仅在第二个 cin.get() 之后才阻止输入。
例如:
Is the number 7 //program doesn't wait after this
Is the number 7 closer to your number than 8 //program blocks here for an input
为什么会这样做?