[英]std::setfill and std::setw for input streams?
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
. 当发送
12
到标准输入时,我期望xx
的值为1200
,而发送12345
我期望它的值为1234
。
However, it seems std::setfill
and std::setw
have no effect and I am getting 12
and 12345
respectively. 但是,似乎
std::setfill
和std::setw
没有效果,我分别得到12
和12345
。
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. 另请注意,当我将
xx
的类型更改为std::string
, std::setw
生效,而std::setfill
仍然无效。
My compiler is gcc-7.0.1
. 我的编译器是
gcc-7.0.1
。
According to C standard, setfill
pertains to output stream. 根据C标准,
setfill
属于输出流。 As for the setw
, it works for input stream when used together with char*
or string
. 至于
setw
,当与char*
或string
一起使用时,它适用于输入流。 For example, following program outputs abcd
for input string abcdef
(and 1234
for 123456
): 例如,以下程序输出输入字符串
abcdef
abcd
(和123456
输出1234
):
string a;
cin >> setw(4) >> a;
cout << a;
setw
and setfill
are not applied so universally. setw
和setfill
并非普遍应用。
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;
}
This function will not trim 12345
to 1234
, though. 但是,此功能不会将
12345
修剪为1234
。 That would take another conversion through string
. 那将需要通过
string
进行另一次转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.