cin.get() is non-blocking

筅森魡賤 提交于 2019-12-02 10:05:03

问题


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.



来源:https://stackoverflow.com/questions/8151548/cin-get-is-non-blocking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!