This is my read_double function. Why do I have to check for !flush_buff() or what is its effect? I somehow cannot figure it out. Couldn't I just write flush_buff() and then return DBL_MIN?
double read_double(void) {
double x;
int c, status;
printf("Insert double: ");
status = scanf("%lf", &x);
if (status == EOF || (c = getchar()) == EOF) {
return DBL_MIN;
}
if (status != 1 || c != '\n' || x < DBL_MIN) {
if (!flush_buff()) { /*What is the purpose of this?*/
return DBL_MIN;
}
return DBL_MAX;
}
return x;
}
The flush_buff function:
int flush_buff(void) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
return c != EOF;
}
The flush_buff()
function fetches characters from stdin until it encounters either a line break (\n
) or end of file (EOF
). If it found a line break (and not EOF
), then it returns a "true" value (equal to 1).
The syntax !flush_buff()
negates this return value, and thus will be false (zero) if flush_buff()
stopped at a line break, or true (1) if the end of file has been reached.
In the code you posted, the value of status
will be 1 if a floating point value was read successfully, 0 if a floating point value could not be read successfully, or EOF
if the input stream ended without providing any input.
If status
is not EOF
, then an additional character c
is read from the input. If this is not a newline character, or if the number provided is outside the range of positive nonzero floating point numbers, then the input is treated as invalid.
As this point, the programmer has decided — for whatever reason — that the function should return DBL_MIN
if the input file ends at the current line, or DBL_MAX
if the current line is terminated by a line break character. The reasoning behind this is unclear.