What could cause a stream to enter the “bad” state?

前端 未结 2 477
有刺的猬
有刺的猬 2021-01-11 15:59

In C++, each stream has a bad bit:

This flag is set by operations performed on the stream when an error occurs while read or writing data

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 16:28

    According to cppreference.com :

    The standard library sets badbit in the following situations:

    • Insertion into the output stream by put() or write() fails for any reason.

    • Insertion into the output stream by operator<<, std::put_money or std::put_time, could not complete because the end of the output stream was reached (The facet's formatting output function such as num_put::put() or money_put::put(), returns an iterator iter such that iter.failed()==true)

    • Stream is constructed with a null pointer for rdbuf(), or putback()/unget() is called on a stream with a null rdbuf(), or a null pointer passed to operator<<(basic_streambuf*)

    • rdbuf()->sputbackc() or rdbuf()->sungetc() return traits::eof() to putback() orunget()`

    • rdbuf()->pubsync() returns -1 to sync(), to flush(), or to the destructor of ostream::sentry on a unitbuf stream

    • Exception is thrown during an I/O operation by any member function of the associated stream buffer (e.g. sbumpc(), xsputn(), sgetc(), overflow(), etc)

    • Exception is thrown in iword() or pword() (e.g. std::bad_alloc)


    This may be one more reason to choose cppreference.com over www.cpluplus.com, see: What's wrong with cplusplus.com?

提交回复
热议问题