2013-01-31 14 views
5

我是C的初學者,所以請原諒我這個問題是愚蠢的還是奇怪的問。在測試真實條件後,如何進行printf?

我讀Ç底漆加和在章-8一個例子是一些環路測試用戶是否進入 - a newline character or not,我無法理解。

的代碼很短,所以我將它展示給你:

int main(void) 
{ 
    int ch; /* character to be printed */ 
    int rows, cols; /* number of rows and columns */ 
    printf("Enter a character and two integers:\n"); 
    while ((ch = getchar()) != '\n') 
    { 
     if (scanf("%d %d",&rows, &cols) != 2) 
      break; 
     display(ch, rows, cols); 
     while (getchar() != '\n') 
      continue; 
     printf("Enter another character and two integers;\n"); 
     printf("Enter a newline to quit.\n"); 
    } 
    printf("Bye.\n"); 
    return 0; 
} 
void display(char cr, int lines, int width) // the function to preform the printing of the arguments being passed 

什麼我不明白這裏是:

while (getchar() != '\n') 
       continue; 
      printf("Enter another character and two integers;\n"); 
      printf("Enter a newline to quit.\n"); 

首先,在while (getchar() != '\n')正在測試的第一章是輸入正確嗎?第二,如果這是真的,繼續如何不滑動printf語句並且首先進行?不是它應該做什麼?

TNX

+1

「我正在讀C primer plus」<---這是你最大的問題!用火殺死那本書! RTFN –

+3

「繼續」只是煙。最好是'while(getchar()!='\ n');'。 –

+0

謝謝分配:) @Daniel Fischer – MNY

回答

7

因爲有while聲明後沒有大括號,只有下一行包含在循環中。因此,continue將繼續while循環,直到找到新行字符,然後繼續執行printf語句。

這是相同的:

while (getchar() != '\n') 
{ 
    continue; 
} 
+2

+1爲了解決問題的人在這裏真正的問題。 – HWende

+0

非常感謝您的回覆!但我雖然如果編譯器看到getchar()函數,它會停止並要求用戶輸入一個字符,然後測試它,然後繼續...所以這個getchar()在測試之前的輸入?@SShaheen – MNY

+1

@Nir當輸入緩衝區中仍然沒有輸入時,'getchar()'只是從緩衝區讀取一個字符。通常情況下,只有在用戶按下Return/Enter之後,'stdin'的輸入纔會被髮送到程序,因此''getchar()'的緩衝區中總會有一個換行符來最終查找。如果緩衝區中沒有未消耗的輸入,並且流未關閉或損壞,則「getchar()」將被阻塞,直到已將輸入傳遞到緩衝區。 –

1

將繼續只是兩個printf之前應用於while -s所以當你進入\n你會得到了最裏面,而回線

printf("Enter another character and two integers;\n"); 
0

continue適用於最接近while循環。

while (stuff) 
    continue; 

相同

while (stuf); 

(注意分號)。

你只是說「保持循環,直到條件成爲假」。

0

這裏while()循環僅與continue語句相關聯。 所以它沒有與printf語句的關係..........

相關問題