I've been learning C on my own and have been re-working a program out of the C Primer book. I was hoping a fresh set of eyes could possibly spot the one issue that I'm having. As you can see by my output vs expected output I would like to get rid of the line "0 is a number". I believe a re-tooling of the while loop is the issue, but I can't seem to get rid of it despite the variations I've tried.
Output:
Enter some integers. Enter 0 to end.
1 two 3 0 4
1 is a number.
two is not an integer
3 is a number.
0 is a number.
Expected output:
Enter some integers. Enter 0 to end.
1 two 3 0 4
1 is a number.
two is not an integer
3 is a number.
#include <stdio.h>
#include <ctype.h>
int get_int(void); //validate that input is an integer
int main(void)
{
int integers;
printf("Enter some integers. Enter 0 to end.\n");
while (integers != 0)
{
integers = get_int();
printf("%d is a number\n", integers);
}
return(0);
} // end main
int get_int(void)
{
int input;
char ch;
while (scanf("%d", &input) != 1)
{
while (!isspace(ch = getchar()) )
putchar(ch); //dispose of bad input
printf(" is not an integer\n");
}
return input;
}// end get_int
integerswould contain 0 before the loop is executed. Using uninitialized variables leads to bugs. If you compile with optimization and warnings, GCC will report that (gcc -O3 -Wallshould do it; I use-Wextratoo routinely). Incidentally, IIRC, on Solaris, the stack is mostly zeroed, so there'd be a fairly good chance thatintegersis zero on entry to the program.