Possible Duplicate:
Program not waiting for cin
I wrote the following code:
#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;
}
No need to worry if you don’t understand the logic because my question is not regarding that.
In the search function, there are two cin.get(), where i need the user to enter a character. My problem is that the the program blocks for input only after the second cin.get().
For example:
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
Why does it do so?
There are at least two problems in your code. The first is that you’re
leaving characters in the buffer after inputting
N. The simplestsolution is to just add a call to
std::cin.ignore( INT_MAX, '\n' );after
std::cin >> N;; a better solution (because it allows for moreerror checking) would be to use
std::getlineto read the completeline, then parse it using
std::istringstream.The second problem is that you’re assigning the results of
std::cin.get()into achar.std::cin.get()returns anint,which may be
EOF. And you really want to check whether it isEOFbefore converting the
inttochar: you cannot check after becauseeither some legal
charwill compare equal toEOF(plaincharissigned), or the
charwill never compare equal toEOF(plaincharis unsigned). The other alternative is to do something like:
each time you want to read a
char. (This might be better in yourcase, since if you do read
EOF, all further calls tostd::cin.get()will return
EOF.)