Reputation:
I'm having trouble with one of my assignments for my C class, the objective is to read the dates from input, parse the dates, and have them output in the m/d/yyyy format. I have most of the code done but I don't know which functions to use to look for the dates and output it in the correct format. I didn't type a printf function yet because I've been trying to get the input first. I also commented out some of the input to show what I've been having trouble with. Here is my code:
#include <stdio.h>
#include <string.h>
int GetMonthAsInt(char *monthString) {
int monthInt;
if (strcmp(monthString, "January") == 0) {
monthInt = 1;
}
else if (strcmp(monthString, "February") == 0) {
monthInt = 2;
}
else if (strcmp(monthString, "March") == 0) {
monthInt = 3;
}
else if (strcmp(monthString, "April") == 0) {
monthInt = 4;
}
else if (strcmp(monthString, "May") == 0) {
monthInt = 5;
}
else if (strcmp(monthString, "June") == 0) {
monthInt = 6;
}
else if (strcmp(monthString, "July") == 0) {
monthInt = 7;
}
else if (strcmp(monthString, "August") == 0) {
monthInt = 8;
}
else if (strcmp(monthString, "September") == 0) {
monthInt = 9;
}
else if (strcmp(monthString, "October") == 0) {
monthInt = 10;
}
else if (strcmp(monthString, "November") == 0) {
monthInt = 11;
}
else if (strcmp(monthString, "December") == 0) {
monthInt = 12;
}
else {
monthInt = 0;
}
return monthInt;
}
int main() {
// TODO: Read dates from input, parse the dates to find the ones
// in the correct format, and output in m/d/yyyy format
char month = NULL;
char day = NULL;
char year = NULL;
char date = NULL;
char dateFormat[100];
int mm;
int i;
while(1) {
getchar(dateFormat[100], date);
if(date == "-1")
break;
// int length = strlen(date); //
// int dateFormat2 = date.(" "); //
// month = .(mm); //
// day = date.; //
// year = date. //
// month = date; //
// mm = .(month); //
if(date[length - 6] == ',' && mm > 0) {
dateFormat[i++] = month + "//" + day + "//" + year;
}
}
return 0;
}
Upvotes: 2
Views: 833
Reputation:
Here is an example implementation that Jonathan Leffler suggested above. This assumes newline terminated dates, and I showed a couple of example formats (you may need to expand this to match your data):
#include <stdio.h>
#include <string.h>
#include <time.h>
#define LEN 100
int main() {
for(;;) {
char s[LEN] = {0};
fgets(s, LEN, stdin);
if(!strcmp(s, "-1"))
break;
const char *formats[] = {
"%h %d, %Y",
"%m/%d/%Y",
};
struct tm tm = { 0 };
for(unsigned i = 0; i < sizeof(formats) / sizeof(*formats); i++) {
char *s2 = strptime(s, formats[i], &tm);
if(s2 && *s2 == '\n') {
// or use strftime()
printf("%u/%u/%u\n",
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_year + 1900
);
break;
}
}
}
return 0;
}
Consider printing out failed dates, say, to stderr, so you can tweak your formats.
Upvotes: 1