一,函数简介
在我们写日期类,或者时钟类题目时经常会遇到需要规定格式,比如2024-3-1要变为2024-03-01,
所以我接下来要介绍的函数就关于这个格式。
一,setw函数
C++ setw() 函数用于设置字段的宽度,语法格式如下:
setw(n)
n 表示宽度,用数字表示。setw() 函数只对紧接着的输出产生作用。当后面紧跟着的输出字段长度小于 n 的时候,在该字段前面用空格补齐,当输出字段长度大于 n 时,全部整体输出。
cout<<setw(11)<<''ret''<<endl;
需要使用头文件:
# include<iomanip>
代码测试:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// 开头设置宽度为 4,后面的 zeeb 字符长度等于 4,所以不起作用
cout << setw(4) << "zeeb" << endl;
// 中间位置设置宽度为 4,后面的 zeeb 字符长度等于 4,所以不起作用
cout << "zeeb" << setw(4) << "zeeb" << endl;
// 开头设置间距为 14,后面 zeeb 字符数为4,前面补充 10 个空格
cout << setw(14) << "zeeb" << endl;
// 中间位置设置间距为 14 ,后面 zeeb 字符数为4,前面补充 10 个空格
cout << "zeeb" << setw(14) << "zeeb" << endl;
return 0;
}
代码结果:
二,setfill函数
setfill函数一般和setw函数一起使用,setw() 默认填充的内容为空格,可以 setfill() 配合使用设置其他字符填充。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setfill('|') << setw(14) << "zeeb" << endl;
return 0;
}
二,关于setw函数和serfill函数的日期类使用例题
题目如图:
题目分析:
题目输出规定格式,月和日为个位时必须使用‘0’来补充。
代码解析:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int year,day,month=1,i;
int ret[13]={31,28,31,30,31,30,31,31,30,31,30,31};
while(cin>>year>>day)
{
while(1)
{
for(i=0;i<12;i++)
{
if(year%4==0&&year%100!=0||year%400==0)
{
ret[1]=29;
}
if(day>ret[i])
{
day-=ret[i];
month++;
}
}
if(month>12)
{
year++;
month=1;
}
else {
break;
}
}
cout << setw(4) << setfill('0') << year<< "-" //年
<< setw(2) << setfill('0') << month << "-" //月
<< setw(2) << setfill('0') << day;
cout<<endl;
}
return 0;
}