这是我好朋友的一篇文章,我读完后受益匪浅,希望大家读读,如果觉得好极了,大家关注关注他,内容真心好。这是原作者:李在奋斗……
setw(int n)是c++中在输出操作中使用的字段宽度设置,设置输出的域宽,n表示字段宽度。只对紧接着的输出有效,紧接着的输出结束后又变回默认的域宽。
当后面紧跟着的输出字段长度小于n的时候,在该字段前面用空格补齐;当输出字段长度大于n时,全部整体输出。
【当n<1时,紧接】
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[3] = {1,2,3};
for (int i = 0; i < 3; i++)
{
cout << setw(0) << a[i];
}
return 0;
}
【当n>1时,要隔离】
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[3] = {1,2,3};
for (int i = 0; i < 3; i++)
{
cout << setw(2) << a[i];
}
return 0;
}
【setw函数只对紧接着的数据有用】
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[3] = {1,2,3};
for (int i = 0; i < 3; i++)
{
cout << setw(2) << a[i]<<4;
}
return 0;
}
setfill()填充】
#include <iostream>
#include <string.h>
#include <iomanip>
using namespace std;
int main()
{
string s = "123";
cout << setw(5) << setfill('*') << s << endl; // 共设置5个空间,用不满的在前面加*,用不满的话不用
return 0;
}