-1

我必须编写 2 个函数。将日期作为字符串接收并检查其是否为 mm/dd/yy 格式的方法;如果其格式不正确,则应对其进行编辑以使其正确。另一个函数应将验证日期转换为格式“月 dd,20yy”。

我很确定我可以处理第二个功能,但我在第一个功能上遇到了麻烦。我只是不知道如何检查它是否采用这种格式......有什么想法吗?

我以为这会起作用,但它似乎没有......

更新代码:

bool dateValidation(string shipDate)
{
    string temp;
    if(shipDate.length() == 8 )
    {
        if(shipDate[2] == '/' && shipDate[5] =='/')
        {
            int tempDay, tempMonth, tempYear;
            //Gather month
            temp = shipDate[0];
            temp += shipDate[1];
            //convert string to int
            tempMonth = temp.atoi;
            temp = "";

            //Gather day
            temp = shipDate[3];
            temp += shipDate[4];
            //convert string to int
            tempDay = temp.atoi;
            temp = "";

            //Gather year
            temp = shipDate[6];
            temp += shipDate[7];
            //convert string to int
            tempYear = temp.atoi;
            temp = "";

            if(tempMonth > 0 && tempMonth <= 12)
            {

                if(tempMonth == 9 ||
                   tempMonth == 4 ||
                   tempMonth == 6 ||
                   tempMonth == 11 ||)
                {
                    if(tempDay > 0 && tempDay <= 30)
                    {
                        if 30 days
                            }
                }
                else if(tempMonth == 2)
                {
                    if(tempDay > 0 && tempDay <= 28)
                    {
                        if 28 days
                            }
                }
                else
                {
                    if(tempDay > 0 && tempDay <= 31)
                    {
                        if 31 days
                            }
                }
            }
        }
    }
}
4

2 回答 2

0

您需要检查 4 件事:

  • 有8个字吗?如果没有,那么甚至不要费心检查其他任何东西。它的格式不正确。
  • 第三个和第五个字符都是'/'。如果没有,那么您仍然没有正确的格式。
  • 检查每一对的有效值。一个月最多有 1 到 31 天,不超过 12 个月,月份范围从 01 到 12。一年可以是任意 2 位数字的任意组合。

这应该注意格式,但如果您想确保日期有效:

  • 检查每个月的有效天数(1 月 31 日,2 月 28 日至 29 日...),并确实检查那些闰年。
于 2012-11-20T02:30:00.160 回答
0

这看起来很像我要评分的项目......如果这是我要评分的项目,您应该验证它是否符合公历。2012 年 1 月 1 日绝对有效,因此您可能想要做的,我希望您考虑的是创建一个 switch 语句来检查格式,例如 1/12/2012 和 10/2/2012,因为这些是有效的。然后从这些中解析出月份和年份。然后验证它们是否在公历的范围内。如果它是用于我猜是的类,您应该考虑将验证编写为与解析函数分开的函数。

所以先问日期是不是太长,是不是太短,不是是哪个版本,然后把dmy传给验证函数。这种模块化将简化您的代码并减少指令。

就像是

bool dateValidation(string shipDate) { string temp;

switch(shipDate.length())
{
     case(10):
        // do what  your doing
        verify(m,d,y);
        break;

     case(8):
        //dealing with single digits
        // verify 1 and 3 are '/' and the rest are numbers
        verifiy(m,d,y);
        break;

     case(9):
        //a little more heavy lifting here 
        // but its good thinking for a new programmer
        verifiy(m,d,y);
        break;
     default:       

      //fail message
        break;
}
于 2012-11-20T04:38:29.673 回答