我一直在学习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
请注意,您当前编写的循环不能保证完全执行。在执行循环之前''integers'可能包含0。使用未初始化的变量会导致错误。如果你使用优化和警告进行编译,GCC会报告('gcc -O3 -Wall'应该这样做;我经常使用'-Wextra')。顺便说一下,在Solaris上,IIRC的堆栈大部分为零,因此在进入程序时'整数'为零的可能性相当大。 –