Originally Posted by
MK27
You might as well convert to numbers using an array, then a for loop which checks against the numbers. If you use a global const char array (month[0]=january, etc.) and two short functions (one which accepts a char* and returns an int, and one which accepts an int and returns a char*) the conversion will be quick and painless both ways. That makes the for loop pretty simple too.
Very good point.
Something like . . .
Code:
const char monthchars[12][] = {"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
int get_month_as_int(char *monthstr) { /* could also pass your struct into here . . . */
if(!strcmp(monthstr, monthchars[0])) return 0;
if(!strcmp(monthstr, monthchars[1])) return 1;
if(!strcmp(monthstr, monthchars[2])) return 2;
/* or make this into a for() loop . . . simpler, like so . . . */
for(x = 0; x < 12; x ++) {
if(!strcmp(monthstr, monthchars[x])) return x;
}
printf("Please type the month in lowercase . . .\n");
return -1;
}
char *get_month_as_str(int monthint) {
return months[monthint]; /* check that monthint is >= 0 && < 12 . . . */
}
Remember to experiment . . . can't go wrong, unless you don't make a backup beforehand.