【发布时间】:2012-09-17 13:12:39
【问题描述】:
我写了以下代码:
#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
为什么会这样?
【问题讨论】:
-
问题出在您没有显示的代码中。编写一个只调用这个函数的简单程序。它会工作得很好。然后开始改变那个简单的程序,添加你当前程序现在所做的事情,直到问题再次出现。然后想想你改变了什么。
-
这是一个常见的“问题”,在本站搜索“cin get flush”...
-
问题是在 main 中的
cin >>之后缺少一些东西。尝试调用该函数两次,第一个get第二次应该可以正常工作。 -
@chris 还是不行。他必须准确定义在
std::cin >> N之后应该提取的内容。