In C++, can you manually set the failbit of a stream? How?

前端 未结 1 1242
日久生厌
日久生厌 2021-02-05 04:42

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

相关标签:
1条回答
  • 2021-02-05 05:17

    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)

    0 讨论(0)
提交回复
热议问题