如何用C打印给定日期

时间:2017-02-19 06:05:35

标签: c date scanf

我是C编程的新手。我试图使用scanf函数要求用户输入日期并在控制台中显示它。所以写了以下代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int date, month, year;
    printf("Please enter the date in the form of dd/mm/yyyy: ");
    scanf("%d/%d/%d", &date, &month, &year);

    printf("the date you entered was:  %d-%d-%d\n", date, month, year);
    return 0;
}

但输出的格式不正确,例如,我输入“10-12-2016”,但我得到的结果是“10-554502544-32766”。伙计们好吗?提前谢谢。

4 个答案:

答案 0 :(得分:2)

scanf()中,您有这种格式 - %d/%d/%d,但您输入的内容为10-12-2016,所以您做错了!

相反,您应该将输入设为 - 10/12/2016%d/%d/%d中的scanf()部分将忽略输入中的/部分。

  

我在10-12-2016输入,但我得到的结果是10-554502544-32766。任何想法的人?

是的,当您提供10-12-2016作为输入时,scanf()仅将10分配给date变量,但不为其他变量赋值。由于其他两个变量monthyear未初始化,因此当您打印变量monthyear的值时,您将获得垃圾值(554502544和32766)。

检查此方法的一种方法:只需初始化变量然后输入。

int date = 0, month = 0, year = 0;
scanf("%d/%d/%d", &date, &month, &year); 

现在,如果您将10-12-2016作为输入,那么您将获得10-0-0作为输出。希望你能理解实际发生的事情!

答案 1 :(得分:1)

scanf()是一个相当愚蠢的工具。它希望格式与您指定的完全一致,如果不是,您会得到奇怪的行为。

您需要完全按照指定输入文本(dd / mm / yy,而不是dd-mm-yy)或更改您的工作方式。

考虑让scanf()扫描一个字符串,然后你自己学习以获得你想要的值 - 你可以更加容忍输入方式的变化,并且更能证明某人试图通过故意给它无效的输入来打破你的程序。

答案 2 :(得分:1)

您需要检查(:ns &env) (:name (:ns &env)) - See the manual page

的返回值
scanf

答案 3 :(得分:0)

#include <stdio.h>
#include <stdlib.h>

int main() {
    int date, month, year;
    printf("Please enter the date in the form of dd press enter then enter mm then press enter then enter year then press enter.. ");
    scanf("%d", &date);
    scanf("%d", &month);
    scanf("%d", &year);
    printf("the date you entered was:  %d/%d/%d\n", date, month, year);
    return 0;
}