扫描功能仅读取输入的4位数

时间:2015-02-23 21:38:34

标签: c scanf

我正在编写一个程序,以便今天和明天打印出来。但是,当我试图获得今天的日期时,scanf函数似乎只读取前四位数字。输出错了。

例如:如果我把它放在08年的1995年,它就像今天一样读取0,将今天的8读取为今天。今天,19岁为今天。

代码是:

//Write a function to print out tomorrow's date

#include <stdio.h>
#include <stdbool.h>

struct date
{
    int month;
    int day;
    int year;
};

int main(void)
{
    struct date today, tomorrow;
    int numberofdays(struct date d);

    //get today's date
    printf("Please enter today's date (mm dd yyyy):");
    scanf("%i%i%i",&today.month, &today.day, &today.year);

    //sytax to find the tomorrow's date
    if(today.day == numberofdays( today))
    {
        if(today.month==12)  //end of the year
        {
            tomorrow.day=1;
            tomorrow.month=1;
            tomorrow.year=today.year+1;
        }
        else    //end of the month
        {
            tomorrow.day=1;
            tomorrow.month=today.month+1;
            tomorrow.year=today.year%100;
        }
    }
    else
    {
        tomorrow.day=today.day+1;
        tomorrow.month=today.month;
        tomorrow.year=today.year;    
    }
    printf("\nTomorrow's date is:");
    printf("%i/%i/%i\n",tomorrow.month,tomorrow.day,tomorrow.year);
    return 0;
}

// A function to find how many days in a month, considering the leap year
int numberofdays( struct date d)
{
    int days;
    bool isleapyear( struct date d);
    int day[12]=
    {31,28,31,30,31,30,31,31,30,31,30,31};
    if(d.month==2&&isleapyear(d)==true)
    {
        days=29;
        return days;
    }
    else 
    {
        days = day[d.month-1];
        return days;
    }
}

//a fuction to test whether it is a leapyear or not
bool isleapyear( struct date d)
{
    bool flag;
    if(d.year%100==0)
    {
        if(d.year%400==0)
        {
            flag=true;
            return flag;
        }
        else
        {
            flag=false;
            return flag;
        }
    }
    else
    {
        if(d.year%4==0)
        {
            flag=true;
            return flag;
        }
        else
        {
            flag=false;
            return flag;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您必须使用%d %d %d以十进制格式扫描输入,因为当您指定%i格式说明符时,如果指定{{1},它会将标准输入的输入视为八进制格式在数字前面。明白!。

编辑:我建议您阅读0的文档。here

此链接中有关scanf()如何与scanf()转化说明符配合使用的重要一行是:

匹配可选的有符号整数;下一个指针必须是指向int的指针。如果以0x或0X开头,则以16为基数读取整数;如果以0开头,则在基数8中读取整数,否则以10为基数读取。仅使用与基础对应的字符。