Here's the task: 1)07/21/2003 2)July 21, 2003
Write a program that reads a date in the first format and prints it in the second format.
I am supposed to use string methods, especially strtok.
Here's my code:
#include <stdio.h>
#include <string.h>
int main()
{
char date[20];
char month[20];
char day[20];
char year[20];
char *token;
char sep[1] = "/";
printf("Enter the date (MM/DD/YYYY): ");
gets(date);
token = strtok(date, sep);
if (token == "01")
{
strcpy(month, "Januray");
}
else if (token == "02")
{
strcpy(month, "February");
}
//continuing in this way
}
else if (token == "11")
{
strcpy(month, "November");
}
else
{
strcpy(month, "December");
}
token = strtok(NULL, sep);
strcpy(day, token);
token = strtok(NULL, sep);
strcpy(year, token);
printf("%s %s, %s", month, day, year);
}
The problem is that the month part always gives December, which means if statements do not work.
CodePudding user response:
writing like this
if (token == "01")
does not do what you think it does, token
points to the start of the string (date), so you are comparing two addresses with each other, instead to compare the actual string contents use strcmp().
if (strcmp(token,"01") == 0)
but the above method is a bit error prone, what if the user enters "1" instead? So a better way would be to convert it to an integer:
char* tokenend = NULL;
int mon = strtol(token, &tokenend, 10);
then you can use mon
in a switch which makes the code a little bit less verbose.
switch(mon) {
case 1:
strcpy(month,"January");
break;
...
default:
fprintf(stderr, "Invalid month entered %s", token);
break;
}
note also that strtok
changes the contents of date
so the original date is no more. if you want to keep the original string then you need to store is separately.
In general you should use fgets
instead of gets
when reading a string from the keyboard since gets
does not limit the number of characters it can read
if (fgets(date, sizeof(date), stdin) != NULL)
{
// and remove the \n
char* p = strchr(date,'\n');
if (p != NULL) *p = '\0';
}