In C++, can you manually set the failbit of a stre

2020-05-25 01:37发布

I am overloading the input stream operator for use with a Time class and would like to manually set the failbit of the input stream if the input doesn't match my expected time format (hh:mm). Can this be done? How?

Thanks!

1条回答
Rolldiameter
2楼-- · 2020-05-25 02:18

Yes, you can set it with ios::setstate, like so:

#include <iostream>
#include <ios>

int main()
   {
   std::cout << "Hi\n";

   std::cout.setstate(std::ios::failbit);

   std::cout << "Fail!\n";
   }

The second output will not be produced because cout is in the failed state.

(An exception seems cleaner to me, but YMMV)

查看更多
登录 后发表回答