2012-09-29 164 views
0

我需要編寫純C的程序。我想,以填補目前與用戶輸入的浮標陣列和我的功能看起來像這樣:scanf驗證用戶輸入

int fillWithCustom(float *array, int size) { 
    float customNumber; 
    for (i = 0; i < size; i++) 
     for (j = 0; j < size; j++) {    
      printf("\n Enter [%d][%d] element: ", i , j); 
      scanf("%f", &customNumber); 
      *(array+i*size+j) = customNumber; 
     } 
    return 1; 
} 

但是,當我輸入錯誤的號碼或字符,迭代繼續結束......(出我進「。一個」爲第一要素,那麼無論對於循環迭代沒有scanf函數的和數組充滿了0

回答

2

唐;噸使用scanf()用戶輸入。它被寫入與格式化數據一起使用。用戶輸入和格式化數據與白天的夜晚不同。使用fgets()strtod()

+0

謝謝,這讓我很好地指出了正確的功能。一切正常。我解答你的答案並接受你的答案。 ;) –

1

檢查scanf函數的返回值從scanf函數的手冊頁:。

RETURN VALUE 
    These functions return the number of input items successfully matched 
    and assigned, which can be fewer than provided for, or even zero in the 
    event of an early matching failure. 

    The value EOF is returned if the end of input is reached before either 
    the first successful conversion or a matching failure occurs. EOF is 
    also returned if a read error occurs, in which case the error indicator 
    for the stream (see ferror(3)) is set, and errno is set indicate the 
    error. 

繼續閱讀數據,直到你得到一些,做:

while(scanf("%f", &customNumber) == 0); 

如果你想失敗,如果用戶輸入錯誤的數據,該做的:

if(scanf("%f", &customNumber) == 0) 
    break; 
+0

我可以在某種程度上像'do {}那樣執行此操作(errorno/*這裏我不知道要設置什麼* /)' 因此我請求正確的編號而沒有錯誤發生? –

+0

您的情況中的錯誤編號爲0,因爲您希望繼續嘗試,直到成功。 –