int main()
{
int a=0;
int b=0;
std::cout<<"Please enter an int: "<<std::endl;
std::cin>>a;
auto old_state =std::cin.rdstate(); // remember the current state of cin
std::cin.clear(); // make cin valid
std::cout<<"Please enter another int: "<<std::endl;
std::cin>>b;// use cin
auto new_state = std::cin.rdstate();
if(old_state==std::istream::failbit&&new_state==std::istream::failbit)
//I tried std::ostream,std::iostream,ios_base they all work.
std::cout<<"Both are failbit!"<<std::endl;
}
我刚看到了C++ Primer上关于IO章节的内容。我尝试了这段代码,惊奇地发现在最后两行中,当我将std::istream
更改为std::ostream
、std::iostream
或std::ios_base
时,它们都能正常工作,只要我输入了两个char
。请有人帮忙用简单的语言解释一下为什么会出现这种情况。非常感谢!
std::endl
。'\n'
会开始一个新行。 - Pete Becker