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

equivalence to printf ("%.4d",x) in c++

我有一个这样的数组:

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

我需要以 XXXX 方式打印 ar 数组中的数字。我有:

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

并且有效(打印 0005001159230781)。当我想使用 cout 时,printf ("%.4d", Pii[i]); 的等效项是什么?

我试过了:

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