Cin.get() 不会等待按键,即使在它之前有 cin.ignore()
Cin.get() does not wait for a keypress even with cin.ignore() before it
我是一个有点新程序员,在下面练习这个程序。无论出于何种原因,在我的程序结束时,编译器完全跳过了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/
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- C++ cin.ignore() 跳过循环
- 更好的方法,而不是在C ++中使用cin.ignore
- C++ - 如何知道在哪里放置 cin.ignore
- C++:忽略第一个 cin.ignore 之后的输入
- cin.ignore() 正在产生不需要的行为
- 如何将光标移动到 cin.clear() 和 cin.ignore() 之后的文本输出末尾?
- C++ cin.ignore and getline in while loop
- CIN被跳过,Cin.ignore不起作用
- CIN.IGNORE删除第一个字符的第二次函数被调用
- cin.ignore(1)之间的分歧是什么?和cin.ignore(n)
- 使用 cin.ignore 和 cin.clear CPP 时的奇怪行为
- 为什么在"cin"后使用 "getline" 时需要 cin.ignore(),而多次使用 "cin" 时不需要?
- getline删除第一个字符;删除cin.ignore();无法解决
- C++怪异的cin.ignore行为
- Cin 不会暂停输入,尽管同时使用了 cin.clear() 和 cin.ignore()
- 当循环不中断时,使用 cin.ignore 和 cin.clear() 来验证输入
- CIN.IGNORE如何与CIN和Getline一起工作
- 尽管Cin.ignore(),CIN不等待输入
- cin.clear() 和 cin.ignore() 不起作用