0

在 C 语言中,我使用 printf("%+10.5d\n", x); 打印整数 x。

我为 C++ io 操纵器编写了一个小测试用例,但输出格式不同:

#include <iostream>
#include <iomanip>
#include <cstdio>

int main(void)
{
        int x = 3;
        printf("%+10.5d\n", x);
        std::cout << std::showpos << std::setw(10) << std::setprecision(5) << x << std::endl;
        return 0;
}

输出是:

./test 命令
       +00003
           +3

我在这里缺少哪个 io 操纵器来获得与 printf 相同的输出?

4

4 回答 4

2

std::setfill
http://www.cplusplus.com/reference/iostream/manipulators/setfill/

带有简短的 if 语句
((x>0) ? "+" : "" )

所以:
std::cout << ((x>0) ? "+" : "" ) << std::setfill('0') << std::setw(10) << std::setprecision(5) << x << std::endl;

于 2011-05-04T15:43:08.790 回答
1

使用 boost::format 您可以以更简洁的格式获得所需的内容。

http://www.boost.org/doc/libs/release/libs/format/doc/format.html

#include <boost/format.hpp>

int main(void)
{
    int x = 3;
    std::cout << boost::format("%+10.5d") % x << std::endl;
    return 0;
}

对于 sprintf 功能,您可以将 cout 行更改为此。

std::string x_string = boost::str(boost::format("%+10.5d") % x);
于 2011-05-04T16:03:55.560 回答
0

在这种特殊情况下,我认为这是不可能的,至少在没有大量工作的情况下是不可能的。在 C++ 中(与 C 不同), precision输出整数时会忽略参数,因此仅使用操纵器无法获得所需的效果(boost::format也不支持它)。您可能必须格式化为字符串,然后 '0'手动添加前缀或插入。

过去,我有一个GB_Format类(这是前命名空间时代),有点像boost::format,但它确实支持所有 Posix 格式规范;为了 "%.<i>n</i>d"工作,我必须自己实现积分转换,而不是使用底层的流转换。类似于以下内容:

std::string
fmtInt( int value, int width, int precision )
{
    unsigned            work = (value < 0 ? -value : value);
    std::string         result;
    while ( work != 0 || result.size() < precision ) {
        result += "0123456789"[ work % 10 ];
        work /= 10;
    }
    result += (value < 0 ? '-' : '+');
    while ( result.size() < width ) {
        result += ' ';
    }
    return std::string( result.rbegin(), result.rend() );
}
于 2011-05-04T17:43:03.160 回答
0

我能得到的最接近的是这个(注意std::internal):

#include <iostream>
#include <iomanip>
#include <cstdio>

int main(void)
{
    int x = 3;
    printf("%+10.5d\n", x);
    std::cout << std::setfill('0') << std::internal << std::showpos << std::setw(10) << std::setprecision(5) << x << std::endl;
    return 0;
}

这仍然不太正确:

    +00003
+000000003

但这是一种改进。

于 2011-05-04T15:51:19.823 回答