cin.get()是非阻塞的

问题描述 投票:1回答:4

我遇到的问题和链接问题中提到的一样。运行程序后,控制台窗口(在VS 2010中)立即消失。我在主函数的最后使用了cin.get();,但问题仍然存在。请问可能的原因是什么?你可以检查一下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;
}

链接 : Windows上的C++ - 控制台窗口只是闪烁和消失。这到底是怎么回事?

c++ visual-studio-2010 visual-c++ console-application
4个回答
2
投票

我的猜测是

default: return 0;

得到执行。

EDIT:

你是对的,这不是问题所在。阅读 这个.

快速修复的方法是。

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

但你可能需要阅读文章来了解更多关于行为的信息。


3
投票

所以在cin.get()之后使用cin.get()时,一定要记得在它们之间加上cin.ignore()。

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

这主要是因为cin会忽略缓冲区中的空白,所以在cin>>order之后,缓冲区中有一个 "newline"(\n),那么你的cin.get只是读取那个\n,然后你的程序成功执行并返回。cin.ignore()将忽略缓冲区中之前的输入。这真的很有帮助!我是中国的学生。

我是一个在中国的学生。你的问题是我能在这里回答的第一个问题。我曾经遇到过和你一样的问题。我希望这能帮助你。忽略我的英语不好,谢谢你。


0
投票

我打赌你打了默认的开关标签(return 0;). 这就绕过了 cin.get() - 你需要一个 cin.get() 每份回报表。


0
投票

可能是你的 cin.get() 是读取终止您的订单输入的新行?您可以尝试调用 cin.get() 两次。

© www.soinside.com 2019 - 2024. All rights reserved.