日期只输入一个整数,而不是C中的日,月和年

时间:2018-01-13 10:37:14

标签: c date int

我想编写一个C程序,通过输入注册日期计算汽车的年数。我只能使用一个int而不是日,月和年作为整数。如果整个日期是int,我怎么能只计算年份?

这是我的代码:

#include <stdio.h>

int main() {
        int inputDateOfFirstUse, ageCalculation, age;

        printf("\nProgram to calculate the age of a car");
        printf("\nPlease enter the date of the first use (in this syntax tt.mm.jjjj): ");
        scanf("%i", &inputDateOfFirstUse);
        ageCalculation = inputDateOfFirstUse - 2018;
        age = ageCalculation;
        printf("\nThe car is %i years old.", age);
        return 0;
}

1 个答案:

答案 0 :(得分:3)

scanf中,您可以使用%*i语法跳过您不关心的值。

#include <stdio.h>

int main() {
        int inputDateOfFirstUse, ageCalculation, age;

        printf("\nProgram to calculate the age of a car");
        printf("\nPlease enter the date of the first use (in this syntax tt.mm.jjjj): ");
        scanf("%*i.%*i.%i", &inputDateOfFirstUse); // Skips day and month, reads only year
        ageCalculation = 2018 - inputDateOfFirstUse;
        age = ageCalculation;
        printf("\nThe car is %i years old.", age);
        return 0;
}