2015-02-23 62 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