2015-02-23 27 views
1

我在写一个程序来获取今天的日子,并在明天打印出来。但是,当我尝试获取今天的日期时,scanf函数似乎只读取前四位数字。输出是错误的。扫描功能只读取输入的4位数

例如:如果我把08 19 1995年,读0作为today.month,8 today.day,19 today.year

的代码是:

//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; 
     } 
    } 
} 
+0

使用'“%i%i%i”'作为格式字符串。 – 2015-02-23 21:43:09

+0

我试过了,但它不起作用。 – silencefox 2015-02-23 21:44:20

+0

你正确的使用'“%d%d%d”'。 '%i'可以读取八进制数,所以08被读作两个数字,08不是一个好的八进制数,所以它被读为0,然后是8. – 2015-02-23 21:47:17

回答

0

你有使用%d %d %d以十进制格式扫描输入,因为如果您指定%i格式说明符,则它将从八进制格式的标准输入中处理输入,前提是您指定0。注意!

编辑:我建议你阅读文档scanf()here

从这个链接,一个重要的线如何scanf()作品与i转换说明是:

匹配是一个符号整数。下一个指针必须是一个指向int的指针。如果以0x或0X开始,则以16为基数读取整数;如果以0开头,则以8为基数读取整数;否则以基数10读取。只使用对应于基地的字符。

+0

'%i'不会将输入视为八进制。 '%o'将输入视为八进制。 '%i'将输入视为十进制,八进制或十六进制,具体取决于前面的'char'。 – chux 2015-02-23 22:51:53

+0

我没有显示是否应将输入视为十进制或八进制输入的前导字符。如何使用它? – silencefox 2015-02-23 23:27:57

+0

@silencefox你可以使用'%d' – YakRangi 2015-02-24 09:28:34