while (fgets(input, 100, stdin) != NULL && input[0] != '\0') {
daytotal = days(input); // input 包含末尾 '\n'
// strcmp(input, "march") 永遠不相等
}
fgets 會將換行符 \n 讀入緩衝區(若空間足夠)。用戶輸入 march 後按 Enter,input 實際為 "march\n",與數組中 "march" 比較失敗,導致函數返回 -1。
input[strcspn(input, "\n")] = '\0'; // 安全截斷換行
scanf 或 gets(不推薦):
scanf("%9s", input); // 自動跳過空白,不含換行,但有緩衝區溢出風險
// gets(input); // C11 已移除,極度不安全
if (strncmp(input, month.name, strlen(month.name)) == 0 && input[strlen(month.name)] == '\n')
while (fgets(input, sizeof(input), stdin)) {
input[strcspn(input, "\n")] = '\0'; // 去換行
if (input[0] == '\0') break; // 空行退出
daytotal = days(input);
// ...
}
days 函數中 tolower 修改了傳入緩衝區,若後續需原始輸入請先複製。months 可定為 const 防止意外修改。int,並 return 0;。