使用scanf检查错误

时间:2017-04-21 12:17:05

标签: c error-handling runtime-error scanf

对于我的作业,用户输入1到9之间的5个整数来表示五个9面骰子卷,然后用它们来计算得分。我们还需要能够检测和无效输入,即1-9之间的5个整数以外的任何输入。问题是当我为我的任务运行自动测试时,当输入少于5件事时我会收到运行时错误。

我的错误检查代码是(忽略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

我不确定如何解决这个问题,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

IMHO立即打破循环通常会产生比维护标志更可读的代码..

在您的情况下,问题是如果scanf失败,您还没有读取该数字,但您想检查它(未初始化的值)是否在1到9之间。该测试甚至不应该发生。 快速失败