我有一个这样的数组:
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::setfill
和 std::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/