用c ++检查日期

时间:2015-08-19 15:27:43

标签: c++ date

#include <iostream>
#include <stdio.h>
#include <cstdlib>

using namespace std;

int main()
{


   int d,m,g;

   int correctly=1;
   cout<<"Insert date \n";
   cin>>d;
   cin>>m;
   cin>>g;

   if (d<1 || m<1 || m>12) correctly=0;
   int numberofdays;
   switch(m)

{
       case 1:
         case 3:
           case 5:
             case 7:
               case 8:
                 case 10:
                   case 12: 
                   numberofdays=31;

        break;


           case 4:
             case 6:
               case 9:
                 case 11:
              numberofdays=30;
              break;

          case 2:
            if (g%4==0 && g%100=0 || g%400==0)
                numberofdays=29;
            else
                numberofdays=28;

            break;

            default:
            numberofdays=0;
}

if (d>numberofdays) correctly=0;

if (correctly==1)

   cout<<"Date is good.\n";

    else
    cout<<"Date is not good.\n";


system ("PAUSE");
return EXIT_SUCCESS;


}

我在尝试使用1或0正确更改值时遇到错误,并且在尝试使用!= 0更改零时我也遇到了2行的错误。我真的不明白这个部分是怎么回事正确完全有效。

1 个答案:

答案 0 :(得分:1)

如何而不是切换案例:

if (m>12 || m<1)
    numberofdays=0;
else{
    int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
    numberofdays=days[m-1]+(m==2 && (g%4==0 && g%100!=0 || g%400==0))?1:0;
}

如果您不了解三元:

if (m>12 || m<1)
    numberofdays=0;
else{
    int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
    numberofdays=days[m-1];
    if(m==2 && (g%4==0 && g%100!=0 || g%400==0))
        numberofdays++;
}

编辑:

更多提示。正如评论中所提到的,你可能意味着使用d,m,y而不是d,m,g。您没有验证年份,您可以将代码移动到另一个函数,因此您不需要正确的变量。

bool validateDate(int d, int m, int g){ //Used g so you don't get too confused
    if(d<1 || d>31 || m<1 || m>12 || g<0) //Not sure if you can have year 0
        return false; //returns false immediately so you don't waste time checking other stuff
    int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
    int numberofdays=days[m-1];
    if(m==2 && (g%4==0 && g%100!=0 || g%400==0))
        numberofdays++;
    return d<=numberofdays;
    //Should also add that the current format for leap years started at a certain year (google says 1582), so you might have to adjust for that.
}

通过以下方式从主要功能中调用它:

if (validateDate(d,m,g))
   cout<<"Date is good.\n";
else
   cout<<"Date is not good.\n";