2017-04-21 59 views
0

對於我的任務,用戶輸入1到9之間的5個整數來表示5個9面的骰子卷,然後用它們計算得分。我們還需要能夠檢測和無效輸入,即1-9之間的5個整數以外的任何內容。問題是,當我爲我的任務運行自動測試時,當輸入少於5件事情時,出現運行時錯誤。使用scanf進行錯誤檢查

我的錯誤校驗碼(忽略countArray的事情,在程序是爲以後):

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

#define TRUE 1 
#define FALSE 0 

#define ARRAY_SIZE 5 

... 

int main(void) { 

    int numbers[ARRAY_SIZE]; 
    int scanFail = 0; 

    int i = 0; 

     ... 

     // Check for if 5 integers between 1 and 9 have been entered 

    while (i < ARRAY_SIZE && scanFail == FALSE) { 

     if (scanf("%d", &numbers[i]) != 1) { 
      scanFail = TRUE; 
     } 

     if (numbers[i] < 1 || numbers[i] > 9) { 
      scanFail = TRUE; 
     } 

     countArray[i] = ARRAY_NOT_COUNTED; 
     i++; 

    } 

    if (scanFail == TRUE) { 
     printf("Invalid Input: 5 integers 1..9 must be supplied.\n"); 
     return EXIT_FAILURE; 
    } 

    ... 

這是自動測試說:

Test10 (1 2 3) - failed (errors) 

    Your program produced these errors: 

    Runtime error: uninitialized variable accessed. 

    Execution stopped here in main() in youChew.c at line 65: 

    \t\t} 
    \t\t 
    -->\t\t if (numbers[i] < 1 || numbers[i] > 9) { 
    \t\t scanFail = TRUE; 
    \t\t} 

    Values when execution stopped: 

    i = 3 
    numbers = {1, 2, 3, 69513217, -22336628} 
    scanFail = 1 
    numbers[i] = 69513217 

    Test 11 (potato) - failed (errors) 

    Your program produced these errors: 

    Runtime error: uninitialized variable accessed. 

    Execution stopped here in main() in youChew.c at line 65: 

    \t\t} 
    \t\t 
    -->\t\t if (numbers[i] < 1 || numbers[i] > 9) { 
    \t\t scanFail = TRUE; 
    \t\t} 

    Values when execution stopped: 

    i = 0 
    numbers = {69515968, 0, 8192, 69513217, -18240628} 
    scanFail = 1 
    numbers[i] = 69515968 

我不是真的確定如何解決它,所以任何幫助表示讚賞。

+0

'i'在哪裏初始化? – Marievi

+0

哎呦我的壞,忘了把它,它是初始化雖然 – Raze

+0

我不能再現你的問題......我運行的代碼,它等待,直到它得到5個元素。 – Marievi

回答

0

恕我直言,立即斷開回路通常產生比保持標誌更可讀的代碼..

在你的情況下,問題是,如果scanf函數失敗,你沒有看過的數量,但要檢查它是否(未初始化的值)介於1和9之間。該測試甚至不應該發生。 快速失敗

+0

因此,在scanfail = TRUE之後放置斷點? – Raze

+0

我會把整個閱讀過程放在一個單獨的函數中,並立即在這些情況下返回失敗。布爾標誌被刪除。 –

+0

是的,工作。謝謝!! – Raze