2012-06-28 62 views
6

我有一个问题,它与此问题在stackoverflow std::cin.clear() fails to restore input stream in a good state上略有相似,但提供的答案对我无效。重置流的状态

现在的问题是:如何重新设置流的状态为'好'?

这是我的代码,我怎么尝试,但状态从来没有设置好再次。我用两条线分开忽略。

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int result; 
    while (std::cin.good()) 
    { 
     std::cout << "Choose a number: "; 
     std::cin >> result; 

     // Check if input is valid 
     if (std::cin.bad()) 
     { 
      throw std::runtime_error("IO stream corrupted"); 
     } 
     else if (std::cin.fail()) 
     { 
      std::cerr << "Invalid input: input must be a number." << std::endl; 
      std::cin.clear(std::istream::failbit); 
      std::cin.ignore(); 
      std::cin.ignore(INT_MAX,'\n'); 
      continue; 
     } 
     else 
     { 
      std::cout << "You input the number: " << result << std::endl; 
     } 
    } 
    return 0; 
} 

回答

11

这里

std::cin.clear(std::istream::failbit); 

实际上并没有清除failbit的代码,它取代流的当前状态failbit

要清除所有的位,只需拨打clear()


在标准中的描述是有点绕口,表述为的其它功能

void clear(iostate state = goodbit);

后置条件结果:然后如果rdbuf()!=0state == rdstate();否则rdstate()==(state | ios_base::badbit)

这基本上意味着下一次调用rdstate()将返回传递给clear()的值。除了有其他问题时,在这种情况下,您也可能会收到badbit

此外,goodbit实际上根本没有一点,但具有清零所有其他位的值为零。

要清除只是的一个特定的位,你可以使用这个调用

cin.clear(cin.rdstate() & ~ios::failbit); 

但是,如果你明确一个标志等依然存在,仍然不能从流中读取。所以这个用途是相当有限的。

+0

在我的书中说:clear(flag)将指定的条件状态设置为有效。我将其解释为:清除指定的错误位。这是不正确的呢? – physicalattraction

+0

这只是清除()清除*所有*标志。清除单个标志有点复杂(并且不太有用)。我在答复中增加了新的部分。 –