2014-02-13 27 views
0

我正在爲我的課程之一編寫代碼,而且我碰到了一堵牆。我需要用戶輸入一個將被用作for循環重複次數的數字。我要求這個數字的第一個循環是一個while循環。我需要確保輸入的值是一個數字,而不是一個字母或特殊字符。如何確保輸入的值是一個數字?

我不知道如何確保它不是字母或特殊字符。

下一個問題是確保for循環只運行指定的次數,即第一次循環中提供的次數。

這就是我到目前爲止所寫的內容。

#include <stdio.h> 

int main() 

{ 

int num_of_scores, n; 
char enter; 
float score=-1, total=0, average; 

do 
{ 
    printf("\n\nEnter the number of quiz scores between 1 and 13: "); 
    scanf ("%d, %c", &num_of_scores, &enter); 
} 
while(num_of_scores<1 || num_of_scores>13/* && enter == '\n'*/); 

printf("\nStill Going!"); 

for(n=0; n<num_of_scores; n++) 
{ 
    printf("\nEnter score %i: ", n+1); 
    scanf ("%f", &score); 
    while(score>=0 || score<=100) 
    { 
     total = total + score; 
     score = -1; 
     break; 
    } 
} 


average = total/num_of_scores; 

printf("\nThe average score is %.0f.\n\n", average); 
return 0; 

}

所以我編輯的代碼一點點。在第一個while循環中有一部分位於註釋中,因爲它在該循環之後使程序結束了。 printf(「仍在繼續」)只是一個測試,以確保該程序得到這麼多。任何進一步的指針?我仍然不確定如何檢查確保沒有輸入號碼。我雖然增加了& & enter =='\ n'會做到這一點,但如果它掛起程序,它是不好的。你提出的很多例子都很好,但是我覺得它們有點混亂。謝謝!

+2

你應該使用它之前初始化值設置爲0。 num_of_scores有可能包含垃圾值。 –

+0

約翰我相信我解決了這個問題。我有嗎? – jeaboswell

回答

1

檢查返回值scanf。每手冊頁:

返回值

這些函數返回匹配成功並分配輸入項目的數量,這可以少於在早期的情況下提供 的,甚至是零匹配失敗。

如果在第一次成功轉換或發生匹配 故障之前達到輸入的結尾,則返回值EOF。如果發生讀取錯誤,則返回EOF,在這種情況下,流的錯誤指示符(請參閱 ferror(3))已設置,並且設置errno表示錯誤。

+0

是的,我在課前聽說過EOF,但我不確定如何測試。任何提示? – jeaboswell

+0

'int i; i = scanf(...);如果(i == EOF){...}' – abligh

0
do{ 
    char ch = 0; 
    num_of_scores = 0; 
    printf("\nEnter the number of quiz scores between 1 and 13: "); 
    if(scanf("%d%c", &num_of_scores, &ch)!=2 || ch != '\n'){ 
     int ch; 
     while((ch=getchar())!='\n' && ch !=EOF); 
    } 
} while(num_of_scores<1 || num_of_scores>13); 
相關問題