【问题标题】:std::setfill and std::setw for input streams?输入流的 std::setfill 和 std::setw ?
【发布时间】:2017-07-20 16:26:29
【问题描述】:

考虑这段代码:

int xx;
std::cin >> std::setfill('0') >> std::setw(4) >> xx;

12 发送到标准输入时,我希望xx 的值是1200,而在发送12345 时,我希望它是1234

但是,std::setfillstd::setw 似乎没有效果,我分别得到了 1212345

这是一个错误还是符合标准?有没有获得预期功能的好方法?

另外请注意,当我将xx 的类型更改为std::string 时,std::setw 会生效,而std::setfill 仍然不会。

我的编译器是gcc-7.0.1

【问题讨论】:

  • 也许我错过了。 input 流操作从什么时候开始支持std::setfill?我知道std::setw 是,但现在std::setfill 也是???
  • 不,这是格式错误的代码。
  • 我认为输入流不支持std::setfillen.cppreference.com/w/cpp/io/manip/setfill
  • xx 将接收您输入的任何值。你需要展示你之后用它做了什么,并且可以格式化
  • 上述代码编译的事实使拥有所需功能的动机合法化。

标签: c++ parsing integer istream setw


【解决方案1】:

根据 C++ 标准,setfill 属于 输出 流。至于setw,当与char*string 一起使用时,它适用于输入流。例如,以下程序输出 abcd 用于输入字符串 abcdef(和 1234 用于 123456):

string a;
cin >> setw(4) >> a;
cout << a;

【讨论】:

    【解决方案2】:

    setwsetfill 的应用并不那么普遍。

    听起来您想模仿在固定宽度列中格式化给定输入的效果,然后重新读取它。该库确实为此提供了工具:

    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.

    不过,此函数不会将12345 修剪为1234。这将需要通过string 进行另一次转换。

    【讨论】:

    • 这非常低效,因为它将数字转换为 int 两次。
    猜你喜欢
    • 1970-01-01
    • 2013-10-21
    • 2012-08-27
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    相关资源
    最近更新 更多