我一直在學習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的堆棧大部分爲零,因此在進入程序時'整數'爲零的可能性相當大。 –