1

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
ildjarn
  • 62,044
  • 9
  • 127
  • 211
111111
  • 15,686
  • 6
  • 47
  • 62

2 Answers2

1

Your code should look like this:

friend std::istream &operator>>(std::istream &is, asound_stanza &stan)
{
    if ( !(is >> stan.index) )
        return is;  //return if couldn't read unsigned int

    if(std::getline(is, stan.name))//go inside ONLY IF read is successful
    {
       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');
    }
    return is;
}

Read the comments in my modification above!

Since this has been discussed so many times, and I've answered many times before, that I don't want to repeat it again. Please read my other answer which explains the very thing:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Thanks, that is a nicer way, but I would like to know WHY it isn't passing on the malformed stanza to the lambda and why it even tries to parse the last one when the ignore should surely set EOF? – 111111 Aug 17 '11 at 19:41
  • @111111: See my answer again. I've explained this before, so read my other answer. – Nawaz Aug 17 '11 at 19:46
  • The above is not bad persay. But personally I would put the two reads into a single if. `if ((is >> stan.index) && (std::getline(is, stan.name)) { /* We got the object */}` – Martin York Aug 17 '11 at 20:17
  • @Martin that is how it is now – 111111 Aug 17 '11 at 20:28
1

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.

Tomek Szpakowicz
  • 14,063
  • 3
  • 33
  • 55
  • Thanks that answered one of my questions as to why it was displaying the behavior it was, however I would love to know why ignore(...max(), '\n'); isn't setting the EOF flag. – 111111 Aug 17 '11 at 19:54
  • @111111: The ignore reads `upto` the EOF (but not past). So it can read all the characters from the stream. It is always the first operation that tries to read past the end of file that fails (or sets the EOF flag). Note: The last good operation will read upto the eof. – Martin York Aug 17 '11 at 20:16