c++ - 等价于 C++ 中的 printf ("%.4d",x)

标签 c++ cout

我有一个这样的数组:

int ar[] = {5, 11, 5923, 781};

我需要打印来自 ar 的数字以 XXXX 方式排列。我有:

for(i = 1; i<=3; i++) printf ("%.4d", Pii[i]);

并且有效(打印 0005001159230781 )。什么相当于 printf ("%.4d", Pii[i]);当我想使用 cout

我试过:

cout.width( 4 );
cout.fill( '0' );
for(i = 0; i<=3; i++) cout << ar[i];

但它似乎只对第一个参数有效(打印 0003115923781 )

最佳答案

使用 std::setfillstd::setw 修饰符

#include <iostream>
#include <iomanip>

using std::cout;
using std::endl;

int main() {
    int ar[] = {5, 11, 5923, 781};
    for (auto ele : ar) {
        cout << std::setfill('0') << std::setw(4) << ele << endl;
    }
}

关于c++ - 等价于 C++ 中的 printf ("%.4d",x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744844/

相关文章:

c++ - 如何从非 Qt C++ 库类向 Qt GUI 提供反馈?

c++ - OpenGL 白色空白屏幕且无响应

c++ - 避免错误的用户输入(当要求的是整数时为字符串)

C++ - 成对映射 - 检查是否存在具有给定第一个坐标的对

c++ - 在定义函数时,使用decltype获取函数返回的类型

c++ - 如果我只需要它在其他线程中的值,我是否应该在一个线程中锁定一个变量,如果我不这样做,为什么它会起作用?

C++ 错误 : no match for 'operator<<'

c++ - 如何修复我的 C++ 大小写切换菜单?

c++ - 在 C++ 中重定向

C++ 管道数据以 block 的形式打印出来