這段程序是為了輸入一個月份(英文單詞),然後返回截止到輸入月份的所有月的天數總和(比如我輸入march,則返回1-3月份天數總和)。函數部分的功能是如果月份輸入正確,就返回總數。如果輸入不正確,那就返回-1。但是運行程序後,每次運行函數都是返回-1。不知道哪裡出了問題,麻煩大家看下。謝謝。
代碼如下:
#include
#include
#include
int days(char *p);
struct month{
char name[10];
char abbrev[4];
int days;
int monumb;
};
struct month months[12]={
{"january", "jan",31,1},
{"february", "feb",28,2},
{"march", "mar",31,3},
{"april", "apr",30,4},
{"may", "may",31,5},
{"june", "jun",30,6},
{"july", "jul",31,7},
{"august", "aug",31,8},
{"september", "sep",30,9},
{"october", "oct",31,10},
{"november", "nov",30,11},
{"december", "dec",31,12}
};
int main(void)
{
char input[10];
int daytotal;
printf("PLS enter the month");
while(fgets(input,100,stdin)!=NULL&&input[0]!='\0')
{
daytotal=days(input);
if(daytotal>0)
printf("The total days is %d.",daytotal);
else
printf("Input is not valid,pls enter again.\n");
puts("pls enter the next input");
}
return 0;
}
int days(char p) _*函數部分**_
{
int i=0;
int total=0;
while( p[i] != '\0' )
{
p[i] = tolower( p[i] );
i++;
}
for(i=0;i<12;i++)
{
total += months[i].days ;
if( strcmp( p, months[i].name) == 0 )
return total;
}
return -1;
}
fgets每次讀入時會把回車也放到字符串裡,造成比較失敗。修改如下:
while(gets(input)!=NULL&&input[0]!='\0')