Reprinted from https://blog.csdn.net/zy122121cs/article/details/52094352
Here we discuss how C++ outputs the data according to the specified number of digits. For example, all the data printed on the screen are output according to 4 digits, and the front is filled with 0 if it is not enough. Two output controls of C++ are used here, setw (number of digits), and setfill (specified characters).
Without further ado, see the code below:
#include <iostream> #include <iomanip>//Be sure to include this c++ header file, very important using namespace std; intmain() { int test[4] = { 1, 12, 123, 1234 }; for (int i = 0; i < 4; ++i) { cout << setw(4) << setfill('0') << test[i] << " "; } cout << endl << endl; return 0; }