-
scanf question
I have the following problem
int day;
int year;
char month[12][10];
printf("Enter date (e.g. January 1 2008)"\n");
scanf("s% d% d% \n",month, &day, &year);
Now if I enter date with a typo, say January 3 19ww,
"year" return a value of 19 and it ignor the typo ww.
On the other hand if I type year, say w990, it returns a garbage value
as (soemthing like -87293775) expected.
But if make the same type of typo for the day, it always return a garbage
value.
My question is why only 19ww return a value 19 and ignore the characters?
And how can I make 19ww return a garbage value so that I can catch it
though a check such as year > 0 || year < 2500 .
-
>scanf("s% d% d% \n",month, &day, &year);
Since you're talking about a runtime issue, I'll assume that the massive errors in this call are simply typos in the post and not in your code.
>My question is why only 19ww return a value 19 and ignore the characters?
That's how scanf works. It reads characters until it finds characters that aren't valid for the conversion specifier. Since w clearly isn't part of any valid integer value, scanf stops reading on it.
>And how can I make 19ww return a garbage value so that I can catch it
Well, the only real problem is with the year and trailing garbage characters. Otherwise scanf will fail and return less than 3 so that you know the date was invalid. If the date is supposed to be on a line by itself, you can check the next character for a newline, and if it's not a newline, assume that the date is invalid:
Code:
if ( scanf ( "%s%d%d", month, &day, &year ) == 3 ) {
if ( getchar() == '\n' ) {
/* Good date */
}
else {
/* Invalid date */
}
}
else {
/* Invalid date */
}
-
Thanks and sorry about %s reversal