I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this? I know that the return value on printf is the
number of printed characters; so if I could somehow get my year
variable to store the leading zeros, I could just run a check:
int dummy = 0;
dummy = printf("%d", year);
if (dummy != 4)
{
...do something...
}
Wait a minute...you started by asking about scanf, and you say you want to
verify the input? Then I'm sure you'd rather not have to print the value
just in order to be able to validate the user input, right?
You certainly don't have to. Let's go ahead and use scanf, because that's
how you say you're doing it (but scanf is essentially useless if you need
serious validation of input. More on that later...):
int count;
int year;
count = scanf("%d", &year);
Note that you must provide the & on year, since scanf has to know /where/
to put the value. count tells you how many "items" were scanned; it could
be 0 if the user didn't type a number. So let's test that:
if (count != 1)
{
printf("Bad input. You lose.\n");
exit(1);
}
(Of course you might choose to do something other than exit here.)
So, how to test for 4 digits? Well, the easiest way I can think of is to
just test for a valid (or invalid) range:
if (year < 1900 || year > 2030) /* or whatever */
{
printf("Bad year. You're outa here.\n");
exit (1);
}
If you /really/ want "any 4 digit number", just test that it is between
1000 and 9999.
So that takes care of that. Now we can improve the input. sscanf is a royal
pain to work with, because if the user just keeps pressing enter, it'll
merrily echo blank lines till doomsday (it ignores leading whitespace,
including newlines). And if the user presses, say, a letter when scanf is
looking for a number, that letter persists on the input stream the /next/
time you try to read a number, further wreaking havoc.
Better to force a single line of input, and then process it. I like to use
fgets to read a line into a buffer, and then sscanf to do the conversion.
sscanf is a lot like scanf, but it reads input from a string buffer instead
of from the standard input. Putting all of that together with some
re-prompting logic, here's a program for you:
#include <stdio.h>
int main()
{
int year;
char buffer[100];
while (1)
{
printf("Please enter a year: ");
fgets(buffer, 100, stdin);
if (sscanf(buffer, "%d", &year) != 1)
printf("that wasn't a number! Try again....\n");
else if (year < 1900 || year > 2030)
printf("Bad year! Must be between 1900 and 2030."
" Try again...\n");
else
break;
}
printf("Success! your year is %d\n", year);
return 0;
}
That is something you can now expand to support as much processing on that
line of input as you please, without running into a slew of problems you'd
get from using just scanf.
Good luck,
-leor