Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Variable base has not been initialized.

You can fix it by giving an invalid value to base as:

int base = 1; // 1 is not in the valid range.
while ((base < 2) || (base > 36)){

or

better use a do-while loop as:

int base;
do{
     cout << "Base (2-36):" << endl;
     cin >> base;
} while ((base < 2) || (base > 36));

The reason why you need the 2nd cin.get() is that, after you read the base value using cin, a \n is left in the buffer. The first call to cin.get() consumes that \n and the 2nd cin.get waits for your input. To avoid this you need to flush the \n from the buffer after cin by calling cin.ignore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top