C++ Logo

std-discussion

Advanced search

Re: IOStreams behavior definition

From: Bo Persson <bo_at_[hidden]>
Date: Tue, 30 Jun 2020 19:20:32 +0200
On 2020-06-30 at 18:35, Philip Prindeville via Std-Discussion wrote:
> Hi.
>
> I’m trying to figure out what the appropriate behavior of std::setw() and std::ios_base::width() should be on a istream. It doesn’t seem to be well defined.
>
> If I have:
>
> istringstream is(“0123456789”);
> unsigned u1, u2;
>
> is >> setw(2) >> u1 >> u2;
>
> cout << u1 << ‘ ‘ << u2 << endl;
>
> I’d expect the output to be “1 23\n” with “4” being the next character on the input stream.
>
> Not the case.
>
> g++ and clang++ both try to consume all available digits into the first argument regardless of width, even overflowing if there are too many digits.
>
> In short, there’s no way to do columnar input if there are no delimiter characters between numbers.
>
> You’d thing this would be a fairly common/obvious usage scenario but it doesn’t seem to be well defined in the IOStreams specification.
>
> http://www.cplusplus.com/reference/iomanip/setw/
>
> Refers to both input and output streams but only describes output behavior concretely.
>
> http://www.cplusplus.com/reference/ios/ios_base/width/
>
> Its homologue width() on the other hand makes no mention of input at all.
>
> Can some clarity be shed on this?
>

Not much. :-)

However, note that setw sets the minimum width for output, not the
maximum width.

Also, operator>> and operator<< can be overloaded for user defined types
and do whatever is needed for that particular type. Some of the iostream
features are added to be useful for that case, even if not necessarily
used by the standard operators.


     Bo Persson

Received on 2020-06-30 12:27:01