Boost logo

Boost :

From: Kevlin Henney (kevlin_at_[hidden])
Date: 2005-01-30 07:45:21


In message <033901c50655$6347e4d0$0300000a_at_pc>, Terje Slettebø
<tslettebo_at_[hidden]> writes
>>From: "Preston A. Elder" <prez_at_[hidden]>
[...]
>> struct my_type
>> {
>> int a;
>> int b;
>> };
>>
>> template<typename C, typename T>
>> std::basic_istream<C,T> &operator>>(std::basic_istream<C,T> &is,
>> my_type &mt)
>> {
>> is >> mt.a >> mt.b;
>> return is;
>> }
[...]
>> The output I get is:
>> TEST 1 FAILED
>> TEST 2: 3 4
[...]
>> My investigation has shown that this occurs because boost::lexical_cast
>> calls stream.unsetf(std::ios::skipws);

Yes, lexical_cast unsets the skipping of whitespace, but that does not,
to my knowledge, introduce problems for correctly written stream
extraction operators.

If reading a representation in and writing it out for a custom type
depends on the skipping of whitespace, the stream extraction operator
must guarantee this -- it cannot assume the state of the input stream
will be what it needs. In other words, there is a bug in the
implementation of operator>>. Here is a simplified (untested and not
exception safe) sketch of the basic logic:

        ... operator>>(... &is, my_type &mt)
        {
                std::ios::fmtflags old_fmt = is.flags();
                is.setf(std::ios::skipws);
                is >> mt.a >> mt.b;
                is.flags(old_fmt);
                return is;
        }

HTH

Kevlin

-- 
____________________________________________________________
  Kevlin Henney                   phone:  +44 117 942 2990
  mailto:kevlin_at_[hidden]     mobile: +44 7801 073 508
  http://www.curbralan.com        fax:    +44 870 052 2289
  Curbralan: Consultancy + Training + Development + Review
____________________________________________________________

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk