Search code examples
c++streamc++11iteratorstl-algorithm

istream_iterator try to parse invalid data


Hi was I hoping someone would help understand this behaviour of the below code.

#include <iostream>
#include <algorithm>
#include <string>
#include <limits>
#include <fstream>
#include <iterator>
#include <stdexcept>


struct asound_stanza
{
    unsigned index;
    std::string name;

    friend std::istream &operator>>(std::istream &is, asound_stanza &stan)
    {
        is >> stan.index;
        if(!is.good())
            return is;
        std::getline(is, stan.name);
        std::string::const_iterator
            eol   = stan.name.cend(),
            start = std::find(stan.name.cbegin(), eol, '['),
            end   = std::find(start, eol, ' ');
        stan.name = std::string(++start, end);
        is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        // std::istream_iterator<char> it;
        // while(*it++!=0x0a);
        return is;
    }
};

int main()
{
    std::ifstream is("/proc/asound/cards", std::ifstream::in); 
    std::istream_iterator<asound_stanza> it(is), end;
    unsigned devid = 0;
    std::for_each(it, end, [&](const asound_stanza &stan)->void{
        if(stan.name!="CODEC")
            return;
        devid = stan.index;
    });
    std::cout << devid;
    return 0;
}

this works, but I have a few questions. after all the valid iterations are done it goes a head and tries to parse another one which inevitably fails (hence the if(!is.good())..._). It tries to parse it but it never passes the final malformed struct onto the lambda expression. Why doesn't it? Is it because the streams is not good() so it doesn't bother trying to pass it in?

Also how can I get it to not even bother try and parse the final struct, (each stanza ends with a newline (0x0a), So I would have thought that ignoring the stream up until the newline would cause an EOF on the final valid iteration but it doesn't.

Thanks for your guidance.

Also feel free to pass on another coding correctness comments.

PS: my file looks like this

0 [Intel          ]: HDA-Intel - HDA Intel
                     HDA Intel at 0xfc500000 irq 46
1 [HDMI           ]: HDA-Intel - HDA ATI HDMI
                     HDA ATI HDMI at 0xfc010000 irq 47
2 [CODEC          ]: USB-Audio - USB Audio CODEC
                     Burr-Brown from TI USB Audio CODEC at usb-0000:00:1d.7-3.1, full speed

Solution

  • If stream is in invalid state or if attempt to read from stream inside operator>> fails and sets stream to invalid state, istream_iterator sets itself to end of stream position. So iteration ends without even looking at partially parsed object.