Consider this code:
int xx;
std::cin >> std::setfill('0') >> std::setw(4) >> xx;
When sending 12
to the standard input I am expecting the value of xx
to be 1200
and when sending 12345
I am expecting it to be 1234
.
However, it seems std::setfill
and std::setw
have no effect and I am getting 12
and 12345
respectively.
Is this a bug or it is according to the standard? Is there a good way to get the expected functionality?
Also note, when I change the type of xx
to be std::string
the std::setw
takes effect while std::setfill
still doesn't.
My compiler is gcc-7.0.1
.
According to C standard, setfill
pertains to output stream. As for the setw
, it works for input stream when used together with char*
or string
. For example, following program outputs abcd
for input string abcdef
(and 1234
for 123456
):
string a;
cin >> setw(4) >> a;
cout << a;
setw
and setfill
are not applied so universally.
It sounds like you want to imitate the effect of formatting the given input in a fixed-width column, then re-reading it. The library does provide tools for exactly that:
int widen_as_field( int in, int width, char fill ) {
std::stringstream field;
field << std::setw( width ) << std::setfill( fill );
field << std::setiosflags( std::ios::left );
field << in;
int ret;
field >> ret;
return ret;
}
Demo .
This function will not trim 12345
to 1234
, though. That would take another conversion through string
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.