这里探讨C++如何将数据按指定的位数输出,如将所有打印在屏幕上的数据都按4位数输出,不够的前面补0。这里要用到C++的两个输出控制,setw(位数),和setfill(指定字符)。
不讲废话了,见下面代码:
#include <iostream>
#include <iomanip>//一定要包含这个c++头文件,非常重要
using namespace std;
int main()
{
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;
}