C++ Logo

std-discussion

Advanced search

Re: IOStreams behavior definition

From: Gennaro Prota <gennaro.prota_at_[hidden]>
Date: Tue, 30 Jun 2020 20:59:56 +0200
On Tue, Jun 30, 2020, 19:02 Philip Prindeville via Std-Discussion <
std-discussion_at_[hidden]> 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.
>

It will work as you expect if you extract into a std::string. Not all
extractors take into account the width (the string extractor does).
Alternatively, you can use the get() member, or, since C++20, extract into
an array of chars.

    [...]
>
> You'd think 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/


If you really must use a non-primary source, I heartedly recommend
cppreference.com over cplusplus.com (but, still, double check with the
standard).

-- 
--
.:: Gennaro Prota ::.
.:: https://about.me/gennaro.prota ::.

Received on 2020-06-30 14:03:24