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!
In C++ stream refers to the stream of characters that are transferred between the program thread and i/o. Stream classes in C++ are used to input and output operations on files and io devices. These classes have specific features and to handle input and output of the program. The iostream.
standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With