Check the validity of a date supplied from the command line in C

#include <stdio.h>
 
void convert(char **,int*,int*,int*);
int valid(int,int,int);
 
int main(int argc,char *argv[])
{
  int d,m,y
  char *progname=argv[0];
 
  if(--argc>0)
  {
      convert(++argv,&d,&m,&y);
      printf("The date %s is %sn",*argv,
               (valid(d,m,y))?"validn": "invalidn");
  }
  else
      printf("Usage: %s dd-mm-yyyyn",progname);
  return 0;
}
void convert(char **ptrarr,int *pd,int *pm,int *py)
{
    char *curptr,c;
    int n;
 
    /*Points to the date string */
    curptr=*ptrarr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *pd=n;
    ++curptr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *pm=n;
    ++curptr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *py=n;
}
int valid(int d,int m,int y)
{
    int   leap;
 
    if(d<0 || d>31 || m<=0 || m>12 || y<=0 || y>5000)
        return 0;
    if((m==4 || m==6 || m==9 || m==11) && d>30)
        return 0;
    if(m==2 && d>29)
     return 0;
  leap= (y%4==0 && y%100!=0) || y%400==0;
  if(m==2 && leap==0 && d>28)
     return 0;
  return 1;
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.