2012-09-27 111 views
-3

我做了一部分代碼的類練習和代碼工作,但我真的不明白髮生了什麼特定的一塊。解釋這個C代碼請

誰能請解釋一下這個部分:

if(scanf("%d%c", &num1, &term1) != 2 || term1 != '\n'){ 

    printf("ERROR! You should type an integer e.g 5, 80, 100\n"); 

} else { .... 

完整的代碼是:

#include <stdio.h> 

int main(){ 

int num1,num2; 

char term1,term2; 

printf("Type your first integer\n"); 

if(scanf("%d%c", &num1, &term1) != 2 || term1 != '\n'){ 

    printf("ERROR! You should type an integer e.g 5, 80, 100\n"); 

} else { 

    printf("Type your second integer\n"); 

    if (scanf("%d%c", &num2, &term2) != 2 || term1 != '\n'){ 

     printf("ERROR! You should type an integer e.g 5, 80, 100\n"); 

    } 

    printf("\n%d", num1); 
    for (int i=0; i<num1; i++) { 
     printf(" *"); 
    } 

    printf("\n"); 

    printf("%d", num2); 
    for (int j=0; j<num2; j++) { 
     printf(" *"); 
    } 
} 
} 

這次演習是爲了使程序請求2個的整數值,使一個水平條形圖與兩個值。

謝謝。

+0

儘量不要只是轉儲一個代碼的負載,而是做一些研究,並要求一個簡短而具體的問題。 – leo

回答

3

scanf()返回它成功接收的術語數。你要求兩個條款,所以你要比較結果以確保兩個條款都已收到。然後您檢查字符項以確保它是回車符,因此您知道用戶在輸入數字字詞後沒有鍵入任何其他文本。

我非常贊同@ Vlad關於閱讀文檔的評論。如果你在沒有任何實際努力的情況下自行解決的問題上發佈幫助,當你面對更復雜的事情時,你註定會失敗。