I am learning C from C Primer Plus, and am still a beginner. I have been introduced to only two functions for input, scanf()
and getchar()
.
According to me, when stdin
is associated with input from a keyboard, there are 4 possibilities for user input in this program:
- User provides valid input and presses enter.
- User provides valid input and triggers EOF.
- User provides invalid input (including no input) and presses enter.
- User provides invalid input (including no input) and triggers EOF.
For (1) and (2), I want the program to continue normally. For (3), I want the program to keep asking the user for valid input. For (4), I want the program to abort.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define PROMPT "Enter a non-negative number: "
double get_valid_input(void);
bool flush(void);
int main(void)
{
double inputNum = get_valid_input();
printf("Your input = %.2f\n", inputNum);
return 0;
}
double get_valid_input(void)
{
double inputNum;
bool endOfFile;
int a;
while ((printf(PROMPT), (a = scanf("%lf", &inputNum)) != 1)
|| ((a == 1) && (inputNum < 0.0)))
{
a = 0;
endOfFile = flush();
if (endOfFile == true)
break;
}
if (a == 0)
exit(EXIT_FAILURE);
else
endOfFile = flush();
return inputNum;
}
bool flush(void)
{
int f;
while ((f = getchar()) != '\n' && f != EOF)
continue;
if (f == EOF)
{
printf("\n");
return true;
}
else
return false;
}
(a == 1)
check is redundant, since it is in the 2nd part of an||
expression. (This comment is redundant, given @Reinderein's reply below, but I include it for completeness.) Also, if you make thePROMPT
, thescanf
format string, and a validation function into parameters, you could have the start of a generic input validation module. \$\endgroup\$