This is what I think the code should look like. It's inside a function (main) by the way.
char a;
if (a [is detected]) {
printf("Incorrect input format \n");
exit( EXIT_FAILURE );
}
This is what I think the code should look like. It's inside a function (main) by the way.
char a;
if (a [is detected]) {
printf("Incorrect input format \n");
exit( EXIT_FAILURE );
}
Remember that digits are also characters. What you want to do is to use scanf
to scan for an integer, and check the return value. The return value from the scanf
family of function is the number of successfully scanned items, or -1
on error. If you scan for a single integer (format "%d"
) then if scanf
doesn't return 1
there was an error.
So you could do something like
if (scanf(" %d", &number) == 1)
{
/* Got a number okay */
}
else
{
/* Not a number in the input */
}
Also remember that if scanf
fails, the input is still there, so you can't just loop and hope the current input will be disregarded. A simply way to get by that is to use fgets
to read one line of input, and then use sscanf
to scan the newly read line.
Use fread
instead of scanf
to read the input from stdin
. Parse the input provided by user to check if char
is given as input, then print the error.