为什么顺序很重要
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()
他们说您忽略了错误)或放弃并退出。
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 以相反的顺序打印数组 - 为什么这在C++中是错误的?
- 为什么切换 for 循环的顺序会显著改变执行时间?
- 为什么切换 if else 语句的顺序会导致错误?
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- if-else 语句仅按特定顺序工作,我不知道为什么
- 为什么重载的函数模板顺序对基本类型很重要
- 为什么结构属性声明和初始化顺序的行为是这样的?
- 为什么'acquire/release'不能保证 c++11 中的顺序一致性?
- 抛出多个异常时,catch 块执行的顺序是什么,为什么?
- 为什么我们将数组称为顺序容器?
- 为什么要以相反的顺序执行RUST功能和FFI C 功能
- 为什么具有顺序一致性的 std::原子存储使用 XCHG
- 为什么按此顺序评估'--++a-- ++ +b--'?
- 为什么当它打破初始化列表的顺序规则时它会起作用
- glm::quat 为什么 x,y,z,w 成分的顺序是混合的
- 为什么更改链接顺序可以修复一个系统上的一些链接错误?
- 为什么在未由语言本身定义的结构字节中的位字段顺序
- 为什么在定义静态成员变量时不遵循定义顺序