Validating help in C
I'm trying t开发者_运维问答o get this validation for a date entered, from Jan 01 1901 to Dec 31 2299, if the date is out of range, give a error message, this is my code, some how it doesn't validate correctly, am I doing something wrong
int main (void)
{
// insert code here...
int day,month,year;
printf("Enter Year, Month and Day as YYYY,MM,DD\n");
scanf("4%d 2%d 2%d", &year, &month, &day);
if (year>1900 && year <2300) {
if (month>=1 && month <=12)
if (day >=1 && day <=31)
printf("correct/n");
else
printf("invalid/n");
}
return 0;
}
The problem is that you're using nested if statements, but you don't have enough else statements. If you simply consolidate the statements it should work.
if (year > 1900 && year < 2300 &&
month > 0 && month < 13 &&
day > 0 && day < 32)
{
printf("correct\n");
}
else
{
printf("invalid\n");
}
If I were doing this, I think I'd start with a small function like:
int in_range(int val, int lower, int upper) {
return val >= lower && val <= upper;
}
Then I'd write something like:
if (in_range(year, 1901, 2299) && in_range(month, 1, 12) && in_range(day, 1, 31))
printf("Corrent\n");
else
printf("invalid\n";
You don't say anything for a number of conditions. Fix:
if (year>1900 && year <2300) {
if (month>=1 && month <=12) {
if (day >=1 && day <=31)
printf("correct/n");
else
printf("invalid/n");
} else {
printf("invalid/n");
} else {
printf("invalid/n");
}
Of course, you could collapse that code to avoid redundancies.
if ( year > 1900 && year < 2300
&& month >= 1 && month <= 12
&& day >= 1 && day <= 31
) {
printf("correct/n");
} else {
printf("invalid/n");
}
I'd move that logic into a function.
int is_valid_date(int year, int month, int day) {
return ( year > 1900 && year < 2300
&& month >= 1 && month <= 12
&& day >= 1 && day <= 31
);
}
if (is_valid_date(year, month, day)){
printf("correct/n");
} else {
printf("invalid/n");
}
精彩评论