为什么顺序很重要

why does order matters?

本文关键字:顺序 为什么      更新时间:2023-10-16

为什么当我放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()他们说您忽略了错误)或放弃并退出。