以8位数字形式输入日期并以英文形式显示

Input a date in 8 digit numerical form and display into English form

本文关键字:文形式 显示 日期 输入 8位 数字 字形      更新时间:2023-10-16

下面是我必须解决的 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);