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

标签 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 相同的输出?

最佳答案

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;

关于c++ - 将 C 格式字符串转换为 C++ io 操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5886076/

相关文章:

C++ vector 迭代 : const vs. const auto 与 no const

c++ - 自定义输出

c++ - 如何禁用 std::cerr?

c++ - 如何编写我自己的操纵器?

c++ - 如何正确实现C++流操纵器endl?

c++ - CMake - FLANN 库不构建(对于 PCL 库)

c++ - C/C++ 中 Delphi 类型的类比

c++ - ostream showbase 不显示零值的 "0x"

c++ - 如何使用execl替代系统

c++ - 运行时解释器真的是 C 程序执行的一部分吗?