Search code examples
c++inputblockingcin

cin.get() not functioning as desired


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?


Solution

  • There are at least two problems in your code. The first is that you're leaving characters in the buffer after inputting N. The simplest solution is to just add a call to std::cin.ignore( INT_MAX, '\n' ); after std::cin >> N;; a better solution (because it allows for more error checking) would be to use std::getline to read the complete line, then parse it using std::istringstream.

    The second problem is that you're assigning the results of std::cin.get() into a char. std::cin.get() returns an int, which may be EOF. And you really want to check whether it is EOF before converting the int to char: you cannot check after because either some legal char will compare equal to EOF (plain char is signed), or the char will never compare equal to EOF (plain char is unsigned). The other alternative is to do something like:

    if ( !std::cin.get( c ) ) {
        //  EOF or error seen...
    }
    

    each time you want to read a char. (This might be better in your case, since if you do read EOF, all further calls to std::cin.get() will return EOF.)