将C格式字符串转换为C ++ io操纵器

时间:2011-05-04 15:39:55

标签: c++ iostream manipulators

在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;
}

输出结果为:

./testcommand
       +00003
           +3

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

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);

答案 2 :(得分: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

但这是一种改进。

答案 3 :(得分: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() );
}
相关问题