Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

c++ - cin.get() not working

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...