c - Printing an integer -
i have user input date, e.g. 'january 10 12' signifying month, day , year. works fine if month 2 digit number, if user enters 'january 12 01' or number 0 in front of 'january 12 1' if month 01 or 'january 12 0' if month 00 instead of input. there form of formatting going wrong?
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef int (*compfn)(const void*, const void*); struct date { int month; int day; //the day of month (e.g. 18) int year; //the year of date }; char* months[]= { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}; int getmonth(char tempmonth[]) { if(strcmp(tempmonth, months[0]) == 0) return 0; if(strcmp(tempmonth, months[1]) == 0) return 1; if(strcmp(tempmonth, months[2]) == 0) return 2; if(strcmp(tempmonth, months[3]) == 0) return 3; if(strcmp(tempmonth, months[4]) == 0) return 4; if(strcmp(tempmonth, months[5]) == 0) return 5; if(strcmp(tempmonth, months[6]) == 0) return 6; if(strcmp(tempmonth, months[7]) == 0) return 7; if(strcmp(tempmonth, months[8]) == 0) return 8; if(strcmp(tempmonth, months[9]) == 0) return 9; if(strcmp(tempmonth, months[10]) == 0) return 10; if(strcmp(tempmonth, months[11]) == 0) return 11; } int sortdates(struct date *elem1, struct date *elem2) { if ( elem1->year < elem2->year) return -1; else if ( elem1->year > elem2->year ) return 1; /* here sure years equal, go on comparing months */ if ( elem1->month < elem2->month ) return -1; else if ( elem1->month > elem2->month ) return 1; /* here sure months equal, go on comparing days */ if ( elem1->day < elem2->day ) return -1; else if ( elem1->day > elem2->day ) return 1; else return 0; } main() { int n; int i; char tempmonth[255]; //used store month until checked scanf("%d", &n); struct date *list; list = (struct date *)malloc((n * sizeof(struct date))); for(i = 0; < n; i++) { scanf("%s %d %d", tempmonth, &list[i].day, &list[i].year); list[i].month = getmonth(tempmonth); } qsort(list, n, sizeof(struct date), (compfn)sortdates); for(i = 0; < n; i++) { printf("%s %d %d\n", months[list[i].month], list[i].day, list[i].year); } }
if want output @ least 2 digits, zeros in front, use %02d
format string instead of %d
.
Comments
Post a Comment