简体   繁体   English

为什么顺序很重要?

[英]why does order matters?

why is it that when i put cin.clear() then cin.ignore() the program works flawlessly, ex: i put in chars and the program doesn't bug.为什么当我cin.clear()然后cin.ignore()程序运行完美,例如:我输入chars并且程序没有错误。

but when i put cin.ignore() first then cin.clear() , the program doesn't stop sending error signals.但是当我先放cin.ignore()然后cin.clear() ,程序不会停止发送错误信号。

how does this work?这是如何运作的?

shouldn't the input be erased and the fail flag unset?不应该删除输入并取消设置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'); clears the stream's error flags to make it readable again, and then tries to skip up to 10 characters to the end of a line.清除流的错误标志以使其再次可读,然后尝试跳过最多 10 个字符到行尾。

cin.ignore(10,'\\n'); cin.clear(); first tries to skip up to 10 characters to the end of a line (which will fail and do nothing if the stream is in an error state), and then it clears the stream's error flags to make it readable again.首先尝试最多跳过 10 个字符到行尾(如果流处于错误状态,这将失败并且不执行任何操作),然后清除流的错误标志以使其再次可读。 Then you go around the loop and attempt again to read the ill-formatted data that caused it to fail last time.然后你绕过循环并再次尝试读取上次导致它失败的格式错误的数据。

If the question is, "why can't I use ignore to discard data from a stream that's in an error state" then, erm, you just can't.如果问题是,“为什么我不能使用ignore来丢弃处于错误状态的流中的数据”,那么,呃,你就是不能。 The way streams are designed to be used is that they go into an error state and sit there doing nothing until you either know how to fix it (and clear() them to say you're ignoring the error) or else give up and quit.流的设计使用方式是它们进入错误状态并坐在那里什么也不做,直到你知道如何修复它(并clear()它们说你忽略了错误)或者放弃并退出.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM