There are a couple of ways; however, have you tried AWK to do this? That, of course, presupposes that you can validate prior to a C program which may not be feasible.
So, parsing functions in C.
You can simply read the field as a string into a buffer then take it apart with pointers to the three fields.
09 will be the first two positions of buf (0 and 1), 03 will be in buf (3 and 4) and 1989 will be from buf (6 - 9). The
strncpu() function comes in handy for that; the
strncpy()function is defined as:
Code:
char *strncpy(char *dest, const char *src, size_t n);
Here's a quick-and-dirty way of doing it:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main (void)
{
char buf [] = { "09-03-1989" };
char mm [3];
char dd [3];
char yy [5];
/* display what we're looking at */
(void) fprintf (stdout, "%s\n", buf);
/* extract month from buf */
(void) strncpy (mm, buf, 2);
mm [2] = '\0';
/* extract day of month from buf */
(void) strncpy (dd, buf + 3, 2);
dd [2] = '\0';
/* extract year from buf */
(void) strncpy (yy, buf + 6, 4);
yy [4] = '\0';
/* display what we did */
(void) fprintf (stdout, "%s %s %s\n", mm, dd, yy);
/*
* from here, convert mm, dd, yy
* to integers and validate them
*/
if (atoi (mm) < 1 || atoi (mm) > 12) {
(void) fprintf (stderr, "Month [%s] is invalid\n", mm);
exit (EXIT_FAILURE);
}
exit (EXIT_SUCCESS);
}
I'll leave it to you to validate the day of the month taking into account the number of days in a given month and February and leap years.
Now, this could be a function, called by a program.
You could convert strings to numeric with the
strtol() rather than
atoi()function; e.g.,
Code:
dd = (int) strtol (day, (char **) NULL, 10);
yy = (int) strtol (yer, (char **) NULL, 10);
Another way to parse is with the
strtok() function; here's a small example of how to do that:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main (void)
{
char buf [BUFSIZ];
char *tokptr, *strptr = buf;
(void) gets (buf);
/* the dash is the token pointer here */
while ((tokptr = strtok (strptr, "-\t")) != (char *) NULL) {
(void) fprintf (stdout, "%s\n", tokptr);
strptr = (char *) NULL;
}
exit (EXIT_SUCCESS);
}
Execute it:
Code:
propg
03-09-1989
03
09
1989
There are all sorts of other ways, too, but the above are simple, efficient (within the confines you gave) and will work for you.
Hope this helps some.