cin.get() is non-blocking

2019-03-02 05:12发布

问题:

I have the same problem as mentioned in the linked question. The console window (in VS 2010) disappears immediately after running the program. I use a cin.get(); at the end of the main function, but the problem still remains. Any idea about the possible reason? You can check out the code in main:

int main()
{
    const int arraysize = 10;
    int order;
    int counter;
    int a[arraysize] = {2,6,4,45,32,12,7,33,23,98};

    cout<<"Enter 1 to sort in ascending order\n"
        <<"Enter 2 to sort in descending order\n";
    cin>>order;
    cout<<"Data items in original order\n";

    for(counter=0;counter<arraysize;counter++){
        cout<<setw(4)<<a[counter];
    }

    switch (order){
        case 1: cout<<"\nData items in ascending order\n";
                selectionSort(a, arraysize, ascending);
                break;
        case 2: cout<<"\nData items in descending order\n";
                selectionSort(a, arraysize, descending);
                break;
        default: return 0;
    }

    for(counter=0;counter<arraysize;counter++){
        cout<<setw(4)<<a[counter];
    }

    cout<<endl;
    cin.get();

    return 0;
}

link : C++ on Windows - the console window just flashes and disappears. What's going on?

回答1:

My guess is that

default: return 0;

get executed.

EDIT:

You're right, that's not the issue. Read this.

The quick fix is:

cout<<endl;
cin.ignore(); // <---- ignore previous input in the buffer
cin.get();

But you might want to read the article for further info on the behavior.



回答2:

So when using cin.get() after cin, you should always remember to add cin.ignore() between them .

cin>>order;
cin.ignore();
/* 
   other codes here
 */
cin.get();

It is mainly because the CIN will ignore the whitespace in the buffer, so after cin>>order, there is a "newline"(\n) in the buffer, then your cin.get just read that \n, then you program successfully executed and return. The cin.ignore() will ignore previous input in the buffer. This really help!

I am a student in China. Your question is the first one I can answer here. I once had the same trouble as you. I hope this helps you. Ignore my poor english and thank you.



回答3:

I bet you hit the default switch label (return 0;). This bypasses cin.get() - you need one cin.get() per return statement.



回答4:

Probably your cin.get() is reading the newline which terminated your order input? You could try calling cin.get() twice.