c - C语言中日期只能输入一个整数,不能输入年月日

标签 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;
}

最佳答案

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;
}

关于c - C语言中日期只能输入一个整数,不能输入年月日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239052/

相关文章:

c - 套接字编程 - 序列化

c - Minimax 不能在井字游戏中正确计分分支

c - 是否可以更快地对 0's 1' 求和?

java - java中基本数据格式转换

bash - 日期 - bash 中没有前导 0 或空格的月份?

ASP.NET GridView TemplateField 调用函数( :int)

F#:如何获取int类型输入的char类型表达式

c - 带位移位的类型转换(C 语言)

JavaScript 日期和时间格式化,

c - C 中带有 AVR atmega8 的意外 float 行为