In addition to the other advice you have received, you still must handle removing any character that causes scanf
to fail. Why? When a matching or input failure occurs with scanf
, all reading from stdin
stops and no more characters are read (leaving the character that caused the problem just waiting to bite you again on your next call to scanf
.
To remedy the problem, you are responsible for accounting for any characters that remain (which you can only determine by checking the return from scanf
. If a matching or input failure occurs, then you can use a simple help function to read and discard all characters up to your next '\n'
or EOF
whichever occurs first, e.g.
void empty_stdin (void)
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
Then simply incorporate that within your code any time you experience a matching or input failure (and when passing control to another area that will take input -- just to make sure the input buffer is clean.
Putting those pieces together, you can do something similar to the following:
#include <stdio.h>
// #include <conio.h> /* don't use conio.h -- it is DOS only */
void empty_stdin (void)
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
int main (void) {
int range,
num,
i,
total = 0;
printf ("how many numbers will you enter: ");
if (scanf ("%d", &range) != 1) {
fputs ("error: invalid input - range.\n", stderr);
return 1;
}
for (i = 0; i < range; i++) {
for (;;) { /* loop continually until you get the input you need */
int rtn;
printf ("\n enter number[%2d]: ", i + 1);
rtn = scanf("%d", &num);
if (rtn == EOF) { /* handle user EOF */
fputs ("user canceled input.\n", stderr);
return 1;
}
else if (rtn == 0) { /* handle matching or input failure */
fprintf (stderr, "error: invalid input, number[%d]\n", i + 1);
empty_stdin ();
}
else /* good conversion, break read loop */
break;
}
total += num; /* add num to total */
}
printf ("\nTotal: %d\n", total);
return 0;
}
Example Use/Output
With an intentional matching failure induced in the input:
$ ./bin/scanftotal
how many numbers will you enter: 4
enter number[ 1]: 10
enter number[ 2]: 20
enter number[ 3]: foo
error: invalid input, number[3]
enter number[ 3]: 30
enter number[ 4]: 40
Total: 100
Look things over and let me know if you have further questions. (and avoid the fate noted in my comment to your question...)