[英]why does order matters?
为什么当我cin.clear()
然后cin.ignore()
程序运行完美,例如:我输入chars
并且程序没有错误。
但是当我先放cin.ignore()
然后cin.clear()
,程序不会停止发送错误信号。
这是如何运作的?
不应该删除输入并取消设置fail flag
吗?
#include <iostream>
using namespace std;
class time
{
private:
int hours;
public:
void getime()
{
do
{
cout << "Enter hours: ";
cin >> hours;
if ( hours < 0 || hours > 23 || cin.fail() )
{
cin.clear();
cin.ignore(10,'\n');
cerr << "invalid time, minutes must be between 0 and 59 " << endl;
}
}while(hours<0 || hours>23);
}
};
int main()
{
time asd;
asd.getime();
return 0;
}
cin.clear(); cin.ignore(10,'\\n');
清除流的错误标志以使其再次可读,然后尝试跳过最多 10 个字符到行尾。
cin.ignore(10,'\\n'); cin.clear();
首先尝试最多跳过 10 个字符到行尾(如果流处于错误状态,这将失败并且不执行任何操作),然后清除流的错误标志以使其再次可读。 然后你绕过循环并再次尝试读取上次导致它失败的格式错误的数据。
如果问题是,“为什么我不能使用ignore
来丢弃处于错误状态的流中的数据”,那么,呃,你就是不能。 流的设计使用方式是它们进入错误状态并坐在那里什么也不做,直到你知道如何修复它(并clear()
它们说你忽略了错误)或者放弃并退出.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.