Example of Why stream::good is Wrong?

后端 未结 5 613
星月不相逢
星月不相逢 2021-01-02 01:43

I gave an answer which I wanted to check the validity of stream each time through a loop here.

My original code used good and looked similar to this:

5条回答
  •  醉梦人生
    2021-01-02 02:30

    They were wrong. The mantra is 'never test .eof()'.

    • Why is iostream::eof inside a loop condition considered wrong?

    Even that mantra is overboard, because both are useful to diagnose the state of the stream after an extraction failed.

    So the mantra should be more like

    Don't use good() or eof() to detect eof before you try to read any further

    Same for fail(), and bad()

    Of course stream.good can be usefully employed before using a stream (e.g. in case the stream is a filestream which has not been successfully opened)

    However, both are very very very often abused to detect the end of input, and that's not how it works.


    A canonical example of why you shouldn't use this method:

    std::istringstream stream("a");
    char ch;
    if (stream >> ch) {
       std::cout << "At eof? " << std::boolalpha << stream.eof() << "\n";
       std::cout << "good? " << std::boolalpha << stream.good() << "\n";
    }
    

    Prints

    false
    true
    

    See it Live On Coliru

提交回复
热议问题