Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 514
Jared Avatar asked Oct 28 '09 22:10

Jared


People also ask

How does a stream work in CPP?

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.

Which is used to create an input stream in C++?

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.


1 Answers

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)

like image 125
Jack Lloyd Avatar answered Sep 18 '22 00:09

Jack Lloyd