即使使用cin.ignore(),Cin.get()也不会等待按键

时间:2016-02-18 00:42:07

标签: c++ cin

我是一名有点新手的程序员。无论出于何种原因,在我的程序结束时,cin.ignore()被编译器完全跳过并直接转到cin.get(),但之前已经有一个按键,所以编译器完全跳过它无需等待按键即可完成程序。我已经尝试将cin.get()和cin.ignore()放在switch case语句中,但是会发生同样的错误。我在网上搜索过这个问题,找不到与我的问题有关的任何内容。这是我的完整代码:

#include <iostream>
#include <cstdlib>
#include <cstring>


using namespace std;
class mobs 
    {
    public:
        mobs();
        ~mobs();
        void define();
        void dismi();
        void getinfo();
        int stat[2];
        string name;
        string bio;
    protected:  


        int health;
        int level;

    };
    mobs dragon;
    mobs::mobs()
    {

        int stat[2];

    }
    mobs::~mobs()
    {


    }

int selection;

void mobs::dismi()
{
    getinfo();
    cout<<"Level:" <<level<<"Health:" <<health <<endl  <<endl <<endl       <<"Name:" <<name  <<"Bio:" <<bio <<endl <<endl;

}

void mobs::getinfo()
{
    define();

}

void mobs::define()
{
    stat[0] = health;
    stat[1] = level;

}


int main()
{   
    dragon.stat[0] = 100;
    dragon.stat[1] = 13;
    dragon.name = "Ethereal Dragon, Dragon of the plane";
    dragon.bio = "A dragon that can only be found in the ethereal plane.This dragon has traditional abilites such as flight and the ability to breath fire.  The Ethereal Dragon's other known abilites are teleportation or magic.";


    cout<<"Welcome to the Mob Handbook. " <<endl <<endl <<"Please make a selection "<<endl;
    cout<<"1.Ethereal Dragon" <<endl<<"2." <<endl<<endl <<">";
    cin>>selection;
    cin.ignore();
    switch(selection)
    {
        case 1:
            dragon.dismi();
            break;
        default:
            cout<<"Invalid input";
            break;  

    }

    cin.ignore();
    cin.get();
}

2 个答案:

答案 0 :(得分:1)

You are reading from an istream without checking the result,这是一种反模式。

您应该检查cin >> selection的结果,看看是否可以从流中读取int。如果它不能,则cin流将处于错误状态,并且进一步尝试从中读取将立即返回,而不是阻止等待输入。

if (cin>>selection)
{
     switch (selection)
     {
     // ...
     }
}
else
    throw std::runtime_error("Could not read selection");

如果添加该检查,您至少可以排除流错误,并可以尝试进一步调试。

答案 1 :(得分:1)

尝试将参数添加到 ignore()。类似的东西:

cin.ignore(100);

cin 中可能有多个字符备份。

http://www.cplusplus.com/reference/istream/istream/ignore/