Печать целого числа - PullRequest
       37

Печать целого числа

1 голос
/ 09 марта 2012

У меня есть пользователь, который вводит дату, например, «10 января 12» означает месяц, день и год. Это работает нормально, если месяц представляет собой двузначное число, однако, если пользователь вводит «12 января 01» или любое число с 0 перед ним, я просто получаю «12 января 1», если месяц был 01 или «12 января 0». 'если месяц был 00 вместо того, что я ввел. Есть какая-то форма форматирования, которая идет не так?

#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 the month (e.g. 18)
    int year; //The year of the 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 you are sure the years are equal, so go on comparing the months */

    if ( elem1->month < elem2->month )
        return -1;
    else if ( elem1->month > elem2->month )
        return 1; 

    /* here you are sure the months are equal, so go on comparing the 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 to store the month until checked

    scanf("%d", &n);

    struct date *list;

    list = (struct date *)malloc((n * sizeof(struct date)));

    for(i = 0; i < 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; i < n; i++)
    {
        printf("%s %d %d\n", months[list[i].month], list[i].day, list[i].year);
    }

}

1 Ответ

3 голосов
/ 09 марта 2012

Если вы хотите всегда выводить как минимум две цифры, с нулями впереди, используйте строку формата %02d вместо %d.

...