2015-09-10 162 views
1

您能否告訴我爲什麼這個循環不斷重複而不讓我讀nDo-while循環不斷重複

int n; 
do 
{ 
    printf("Height: "); 
    scanf("%d",&n); 
} 
while(n < 0 || n > 23); 

我無法輸入任何值,因爲「高度:」不斷重複。這裏是完整的代碼:

#include <stdio.h> 
#include <stdlib.h> 
int main() 
{ 
    int n,i,j,k; 
    do 
    { 
     printf("Height: "); 
     scanf("%d",&n); 
    } 
    while(n < 0 || n > 23); 

    for(i=0;i < n;i++) 
    { 
     for(j=0;j < n - i - 1;j++) 
     { 
      printf("%c",' '); 
     } 
     for(k=0;k < i + 2;k++) 
     { 
      printf("%c",'#'); 
     } 
     printf("\n"); 
    } 
} 
+1

你是什麼意思「讓我讀n」?代碼要求輸入一個高度,如果它是負值或大於23,它會再次詢問,否則它會停止。 –

+2

@ 0RedDevil0你進入了什麼? – BLUEPIXY

+1

如果你明確告訴讀者你有什麼問題,它會提高你獲得有用答覆的機會。目前還不清楚你的代碼在做什麼(或不做什麼),這與你的期望不同。閱讀[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)可能會給你一些想法。 –

回答

3

檢查scanf的返回。在這種情況下,如果scanf成功,它將返回1.如果它不返回1,那麼會產生無效輸入,例如www。在這種情況下,清除緩衝區並重試。

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int i = -1; 

    do { 
     printf ("height \n"); 
     if (scanf ("%d", &i) != 1) {// != 1 means scanf failed 
      while ((i = getchar()) != '\n' && i != EOF) { 
       ;//clear buffer 
      } 
      i = -1; 
     } 
    } while (i < 0 || i > 23); 

    return 0; 
} 
+0

請注意,沿線的某處應該處理EOF,以便外部循環在EOF上退出。 –

0

那麼,如果你的值爲n大於23,該循環將永遠打印。我也想知道你的第一個條件是否提供條件「是假的」或「大於23」。您應該嘗試記錄n以查看它提供給循環的內容,如果它大於23,可能會爲循環設置上限。