Using break and continue
suggest changecontinue skips the rest of this iteration when the character is not a digit. break leaves the loop on end-of-file or when the user enters 0. Only the first character of each line is summed. Any later characters on that line are discarded.
isdigit’s argument must be EOF or representable as unsigned char. getchar returns values in that range. The end-of-file test has to come first: after break, isdigit is not called.
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for printf() and getchar() */
#include <ctype.h> /* for isdigit() */
void flush_input_stream(FILE * fp);
int main(void)
{
int sum = 0;
printf("Enter digits to be summed up or 0 to exit:\n");
do
{
int c = getchar();
if (EOF == c)
{
printf("Read 'end-of-file', exiting!\n");
break;
}
if ('\n' != c)
{
flush_input_stream(stdin);
}
if (!isdigit(c))
{
printf("%c is not a digit! Start over!\n", c);
continue;
}
if ('0' == c)
{
printf("Exit requested.\n");
break;
}
sum += c - '0';
printf("The current sum is %d.\n", sum);
} while (1);
return EXIT_SUCCESS;
}
void flush_input_stream(FILE * fp)
{
size_t i = 0;
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF) /* Pull all until and including the next new-line. */
{
++i;
}
if (0 != i)
{
fprintf(stderr, "Flushed %zu characters from input.\n", i);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents