Cin.get() 不会等待按键,即使在它之前有 cin.ignore()

Cin.get() does not wait for a keypress even with cin.ignore() before it

本文关键字:cin ignore get 等待 Cin      更新时间:2023-10-16

我是一个有点新程序员,在下面练习这个程序。无论出于何种原因,在我的程序结束时,编译器完全跳过了cin.ignore((并直接移动到cin.get((,但是之前已经有按键了,所以编译器完全跳过它并完成程序而不等待按键。我尝试将 cin.get(( 和 cin.ignore(( 放在开关大小写语句中,但发生了相同的错误。我已经在网上搜索了这个问题,找不到与我的问题相关的任何内容。这是我的完整代码:

#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();
}

您正在从istream读取而不检查结果,这是一种反模式。

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

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

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

尝试添加一个参数来忽略((。像这样:

cin.ignore(100);

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

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