Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
606 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...