Originally Posted by
gratiafide
How about this?
Code:
float num_check (int tester, float num_entd)
{
while((num_entd>1000) || (num_entd<0) || tester=0)
{
printf("Please enter a valid weight between 0 and 1000 lbs\n");
tester=scanf("%f", &num_entd);
}
return num_entd;
}
That only handles the case where scanf returns 0. You need to check the case where it returns EOF (to indicate that there's no more data on stdin, or an error has occurred.) Since you've chosen an interactive design for your program, the following should be sufficient for your purposes:
Code:
#include <ctype.h>
#include <stdio.h>
static int discardline(FILE *stream)
{
int c;
while ((c = getc(stream)) != '\n' && c != EOF)
;
return c;
}
int readf(float *to, float min, float max)
{
const char *invalid = "invalid character: %c";
int r;
if ((r = scanf("%f", to)) == EOF)
return EOF;
if (!r) {
warn(invalid, getchar());
return discardline(stdin) == EOF ? EOF : 1;
}
while ((r = getchar()) != EOF && r != '\n')
if (!isspace(r)) {
warn(invalid, r);
return discardline(stdin) == EOF ? EOF : 1;
}
if (*to < min) {
warn("%f < %f", *to, min);
return 1;
}
if (*to > max) {
warn("%f > %f", *to, max);
return 1;
}
return 0;
}
Using that function is fairly straightforward. It returns EOF if there's no more input, 0 if a value was successfully converted and stored in 'to', and 1 if there was an error on the line.