这是我整理的星期搜寻计划。一切都按照应有的方式运作,但有一件事我在找出问题时遇到了麻烦。 它将采用的唯一日期格式是dd / mm / yyyy。
我不理解的是: 有一个函数通过确保输入的日期在月份的范围内并且月份的值<12来检查输入的日期是否有效。每次输入8月或9月的日期(08和09月),都无法阅读。经过一些调试后,似乎输入了这些值(输入示例:01/08/2014),sscanf(“%i%i%i”,日,月,年)返回2而不是3,因此它认为条目无效。我无法弄清楚为什么它适用于任何其他日期,但在8月或9月没有任何日期。
该计划:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 15
typedef char* string;
string weekDay[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int month_days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
//Function prototypes
void getInput(string prompt, int* day, int* month, int* year);
bool dateChecking(int *day, int *month, int *year);
bool isLeapYear(int year);
int getCenturyValue(int year);
int getYearValue(int year);
int getMonthValue(int month, int year);
//Read in the date to be analyzed.
void getInput(string prompt, int* day, int* month, int* year)
{
int success;
char buffer[SIZE];
do
{
printf("%s", prompt);
fgets(buffer, sizeof(buffer), stdin);
success = sscanf(buffer, "%i/%i/%i", day, month, year);
if ((success < 3) || !(dateChecking(day,month,year)))
printf("You made an invalid entry. Please try again.\n");
}while ((success <3) || !(dateChecking(day,month,year)));
}
//Check if the day and months are withing allowable ranges.
bool dateChecking(int *day, int *month, int *year)
{
if (isLeapYear(*year))
month_days[1] = 29;
if (*month < 13)
return (*day < month_days[*month-1]);
else return false;
}
//Returns true if the year is a leap year.
bool isLeapYear(int year){
return ((year%400 == 0) || ((year%4 == 0)&&(year%100 !=0)));
}
//Extract the first two digits of the year, and process it
//according to the assignment spec.
int getCenturyValue(int year) {
int value = year/100;
return 2*(3 - (value % 4));
}
//Extract the last two digits of the year, and process it
//according to the assignment spec.
int getYearValue(int year){
int value = year - ((year/100)*100);
return value + (value/4);
}
//switch statement to relate each month to its value
int getMonthValue(int month, int year){
int value = 0;
switch (month) {
case 1: value = isLeapYear(year)? 0 : 6; break;
case 2: value = isLeapYear(year)? 3 : 2; break;
case 3: value = 3; break;
case 4: value = 6; break;
case 5: value = 1; break;
case 6: value = 4; break;
case 7: value = 6; break;
case 8: value = 2; break;
case 9: value = 5; break;
case 10: value = 0; break;
case 11: value = 3; break;
case 12: value = 5; break;
}
return value;
}
int main()
{
int day, month, year, sum;
getInput("Enter a date in the following format: dd/mm/yyyy: ", &day, &month, &year);
sum = day + getMonthValue(month,year) + getYearValue(year) + getCenturyValue(year);
printf("The date specified is a: %s", weekDay[sum % 7]);
printf("\n\n\n");
return 0;
}
答案 0 :(得分:5)
您需要使用%i
将%d
更改为sscanf
。使用%i
将前缀为0
的数字解释为八进制。