-
Input Validation!
Hello everyone.
Right, it's a simple setup for my program, it reads in a number (as an int) and then does something with it. But, as everyones probably noticed if you type in a character the program 'crashes'. I have the following code:
Code:
#include <stdio.h>
void main()
{
int temp;
printf ("Input your number: ");
while (scanf("%d", &temp) != 1)
{
while (getchar() != '\n');
printf ("Try again: ");
}
printf ("You entered %d\n", temp);
}
but I don't understand what the return value from scanf and the new line character have to do with checking for a letter! Is there an easier way of doing this? (I usually use fgets to get an input). Any help with this would be greatly appreciated.
Cheers,
Chris.
-
> but I don't understand what the return value from scanf
scanf() returns the number of conversions AND assignments.
Since a letter fails a conversion to int, scanff() will return 0 in that case
> and the new line character
That's to throw away all the characters which scanf() failed to use. Since you don't know how many (or what they are), you have to go with one you can reasonably expect to find - and thats a newline
> I usually use fgets to get an input
Yeah - fgets() and sscanf() is far superior in this case.
Oh, and main returns an int.
-
cheers salem! i understand whats actually happening now!