Thread: ostream valid flag?

  1. #1
    Registered User
    Join Date
    May 2003

    ostream valid flag?

    I have a suspicion this is a trivial problem, but I can't figure out the vocab to do a decent google/forums search on it.

    I'm writing a class member function that takes an ostream as an argument and then outputs some formatted private member data. I'm curious if there is a way to check to see if it is valid to use the stream insertion operator, for example if the client driver passes an ifstream that hasn't been succesfully opened. I don't really understand that possible states and flags of an ostream, and the references I've looked through so far deal with file streams and standard output streams (cout/cerr) as different topics so I'm not which information applies to all ostreams.

    My code looks something like this:
    void MyClass::printData(std::ostream& out) {
        // if (cannot write to out)
        // throw domain_error;  // or more appropriate exception?
        out << data << std::endl;
    Thank you

  2. #2
    Registered User
    Join Date
    Jan 2003
    The easy answer is
    bool MyClass::printData(std::ostream& out) {return out << data << std::endl;}
    The most significant states are
    s.good() -- all previous operations worked, next operation is expected to succed
    s.eof() -- next operation will fail (end of file) -- prev operation failed, no data lost
    s.bad() -- The wings have fallen off, data lost, stream courrupt

    In a boolean context a stream (and os << a returns os) is cast to a void * that is null iff failbit or badbit are set, and a pointer as a boolean is false iff null. In general you should not throw exceptions for stream failures as the caller can set the stream to do this itself via ios::exceptions()

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. need help on error handling.
    By broli86 in forum C Programming
    Replies: 9
    Last Post: 06-19-2008, 11:55 AM
  3. recursion error
    By cchallenged in forum C Programming
    Replies: 2
    Last Post: 12-18-2006, 09:15 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Stupid compiler errors
    By ChrisEacrett in forum C++ Programming
    Replies: 9
    Last Post: 11-30-2003, 05:44 PM