Reputation: 77
I'm trying to take the date as dd/mm/yy
format, but when I write it like this, it gives me an output as 191/033/0
for 19/07/14
input.
#include <stdio.h>
int main(){
int d1, d2, m1, m2, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d,%d/%d,&,d/%d", &d1,&d2,&m1,&m2,&year);
return 0;
}
How can I fix this?
Upvotes: 0
Views: 53283
Reputation: 53006
You need the strftime()
function, and handle the input correctly so nothing unexpected happens
This is an example of how to do it
#include <stdio.h>
#include <time.h>
#include <string.h>
int main()
{
char buffer[100];
struct tm date;
memset(&date, 0, sizeof(date));
printf("Enter date (dd/mm/yy): ");
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
return -1;
if (sscanf(buffer, "%d/%d/%d", &date.tm_mday, &date.tm_mon, &date.tm_year) == 3)
{
const char *format;
format = "Dated %A %dth of %B, %Y";
if (strftime(buffer, sizeof(buffer), format, &date) > sizeof(buffer))
fprintf(stderr, "there was a problem converting the string\n");
else
fprintf(stdout, "%s\n", buffer);
}
return 0;
}
Upvotes: 1
Reputation: 44838
# include <stdio.h>
int main(){
int d, m, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d/%d/%d", &d,&m,&year);
if (d%10==1 && d!=11) printf("%d st",d);
else if (d%10==2 && d!=12) printf("%d nd",d);
else if (d%10==3 && d!=13) printf("%d rd",d);
else printf("%d th",d);
return 0;
}
By the way, dd/mm/yy
does not mean 'two days, two months and two years'. This means 'two digits for day, month and year'. That's why you don't need so many variables.
Upvotes: 3