cin.get() not working

calccrypto picture calccrypto · Sep 23, 2010 · Viewed 15.6k times · Source

I wrote this simple program today, but I found that cin.get() refuses to work unless there are 2 of them. Any ideas?

#include <iostream>
using namespace std;

int main(){
    int base;
    while ((base < 2) || (base > 36)){
          cout << "Base (2-36):" << endl; 
          cin >> base;
          }
    string base_str = "0123456789abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < base; i++){
        for (int j = 0; j < base; j++){
            for (int k = 0; k < base; k++){    
                cout << base_str[i] << base_str[j] << base_str[k] << endl;
            }
        }
    }
    cin.get();
    cin.get();
}

if i move a cin.get() to before the nested loops, the loops run then pause. if i take one cin.get() out, the program just ends. im using the latest version of bloodshed c++ dev

Answer

user197015 picture user197015 · Sep 23, 2010

You are not initializing the 'base' variable, but while that will cause bugs it isn't (directly) related to the behavior you're seeing with cin, even though it will sometimes, depending on the compiler, cause you to skip loops. You're probably building in debug mode that zero-initializes or something.

That said, assuming that was fixed:

When you type a value (say, 5) and hit enter, the data in the stream is 5<newline> -- operator<< does not extract the newline from the stream, but cin.get() does. Your first cin.get() extracts that newline from the stream, and the second wait waits for input because the stream is now empty. If you had only the one cin.get() call, it would extract the newline immediately and continue, and since there is nothing after that cin.get() call, the program terminates (as it should).

It seems that you're using cin.get() to stop your program from closing when run from the debugger; you can usually do this via a specific "start without debugging" command from your IDE; then you won't need to abuse cin.get() for this purpose.