我一直在自学 C,并且一直在根据 C Primer 书重新编写程序。我希望有一双新的眼睛可能会发现我遇到的一个问题。正如您从我的输出与预期输出中看到的那样,我想去掉“0 是一个数字”这一行。我相信对 while 循环的重新工具是问题所在,但尽管我尝试了各种变化,但我似乎无法摆脱它。
输出:
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.
预期输出:
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