以8位数字形式输入日期并以英文形式显示
Input a date in 8 digit numerical form and display into English form
下面是我必须解决的 c++ 问题,我从第 2 位遇到了一些麻烦(
1(提示用户以8位数字形式输入日期(MMDDYYYY( 例如04221970
2( 以英文形式显示日期 例如 1970年4月22日
3( 如果用户输入的日期是 01,21,31,请在日期后添加"st">
4(否则,如果用户输入的日期是02,22,则在日期后添加" nd">
5( Elae 如果用户输入的日期是 03,23,请在当天后添加"rd">
6(否则在一天后添加"th">
所有步骤都相当简单。 但是日期总是很棘手,因为有很多规则。 但只有一对夫妇申请解析。
定义一个结构来保存分析的值并分析输入。
[编辑] 使用结构的价值在于,拥有一个返回此可重用二进制数据的中间函数可能很有用。
struct date_s
{
unsigned int day;
unsigned int month;
unsigned int year;
};
// parsing
date_s date = {};
if (strlen(input) != 8 || sscanf(input, "%2u%2u%4u", &date.month, &date.day, &date.year) != 3)
{
// handle error
}
验证年份相当容易,无需执行任何操作,除非您要限制在特定范围内。 例如,由于我们使用的是公历,因此您可能希望限制为 1582 年(含(之后的年份。
验证月份也非常简单,我们将验证一个月中的天数,这是最棘手的部分,因为 Febuary。
unsigned int day_max = 0;
switch (date.month)
{
case 1: case 3: case 5; case 7: case 8: case 10: case 12:
day_max = 31;
break;
case 4: case 6: case 9: case 11:
day_max = 30;
break;
case 2:
if (date.year % 4 != 0)
day_max = 28;
else if (date.year % 100 != 0)
day_max = 29;
else if (date.year % 400 != 0)
day_max = 28;
else
day_max = 29;
break;
// else day_max stays 0, of course
}
if (date.day < 1 || day_max < date.day)
{
// error
}
完成所有验证后,您所要做的就是打印。
对于月份,您需要定义一个字符串表以进行显示。
const char* MONTH[12] = { "January", /* etc... */ };
日期后缀。
const char* SUFFIX[4] = { "st", "nd", "rd", "th" };
我们现在拥有了需要打印的所有数据,并且都在范围内。
const char* suffix = SUFFIX[std::min(date.day, 4) - 1];
printf("%d%s %s %d", date.day, suffix, MONTH[date.month - 1], date.year);
// or, for US format
printf("%s %d%s, %d", MONTH[date.month - 1], date.day, suffix, date.year);
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 正在查找文档以获得PS4平台的C++中的设备信息
- 以8位数字形式输入日期并以英文形式显示
- "Time"库形式 Arduino 显示不正确的值
- 以C++显示浮点类型的二进制表示形式
- QT插槽和信号,显示第二形式/窗口
- 从字节数组快速转换为图像,QT可以以形式显示
- 文件的解密显示原始文本和密文
- 在Qt中以列表或表格的形式动态显示多个图像的最佳方法
- 占位符文本 文本字段中的文本在使用输入掩码时不显示
- 如何在终端上显示星号(*)形式的输入密码
- Mongocxx:如何反向显示文档
- c++ MFC MDI如何根据活动文档更改类视图显示的内容
- VS2012如何通过智能感知显示标准c++库的文档
- 为什么从文档 OpenCV 剂量中找到的源代码人脸检测没有显示任何东西
- 以线条形式显示提升矩阵.想要将其更改为 Box
- 如果同时运行两次wkhtmltopdf库,为什么它只会发生数据文档,而没有任何表或图像显示在html文件中
- MFC如何通知文档被更改(并显示*)
- 显示同一文档的多个同时视图
- 它应该以表的形式显示,但它在编译后显示在控制台中的一行中