开发者社区> 问答> 正文

C语言一个简单程序设计问题,找不出原因。

这段程序是为了输入一个月份(英文单词),然后返回截止到输入月份的所有月的天数总和(比如我输入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;
}

展开
收起
a123456678 2016-03-23 16:25:39 1812 0
1 条回答
写回答
取消 提交回答
  • fgets每次读入时会把回车也放到字符串里,造成比较失败。修改如下:

    while(gets(input)!=NULL&&input[0]!='\0')
    
    2019-07-17 19:11:29
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Go语言路上踩过的坑 立即下载
为什么要学函数式编程? 立即下载
属兔的处子——Clojure太灵活,臣妾驾驭不住啊 立即下载