简体   繁体   English

输入流的std :: setfill和std :: setw吗?

[英]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::setfillstd::setw没有效果,我分别得到1212345

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::stringstd::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. setwsetfill并非普遍应用。

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. 但是,此功能不会将12345修剪为1234 That would take another conversion through string . 那将需要通过string进行另一次转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM