A user inputs a float value. The scanf() function gets the value.
However, I need to create an error handler with an if else statement
saying invalid input if the input is not a number. Does anybody know
how I could do this?
Try to be more specific. At the most basic level, you could write
int ret;
...
input_the_number:
ret = scanf("%d", &number);
if (ret != 1) {
printf("That was not a number; try again!\n");
goto input_the_number;
}
if (number < 0) {
printf("That was negative; try again!\n");
goto input_the_number;
}
...
(Or equivalent stuff with more advanced control-flow structures, but I'm
too tired to work out where everything would go in a 'while' loop.)
At a more advanced level, the concept of "error handling" is a pretty
interesting one. I myself am a fan of the following little function:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
static char *Argv0;
void do_error(const char *fmat, ...);
int main(int argc, char *argv[])
{
Argv0 = argv[0];
if (0 == 1) {
do_error("Oh dearie me: %d %d %d\n", 0, 1, 0==1);
}
return 0;
}
/** This is the interesting bit. */
void do_error(const char *fmat, ...)
{
va_list ap;
printf("%s: ", Argv0);
va_start(ap, fmat);
vprintf(fmat, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
In case you can't figure it out from the code, the do_error function
takes a variable number of arguments, just like 'printf', but before
printing them, it tries to print the name of the executing program,
and then, once everything is printed, it terminates the program
directly. This is for those "no recovery possible" sorts of situations,
which may or may not apply to your problem.
As you may know, and unlike C++, C does *not* support exception handling
at the language level. (Anyone got a nice throw/catch sort of idiom for
standard C?
HTH,
-Arthur