c - 使用 scanf 进行错误检查

标签 c error-handling runtime-error scanf

对于我的作业,用户输入 1 到 9 之间的 5 个整数来表示 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

我不太确定如何修复它,因此非常感谢您的帮助。

最佳答案

恕我直言,立即打破循环通常会产生比维护标志更可读的代码..

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

关于c - 使用 scanf 进行错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43542518/

相关文章:

c++ - 向 Java 开发人员的 Eclipse Oxygen IDE 添加 C/C++ 语言

php - 这种方法是否足够好/足够安全以向用户显示错误? - PHP

algorithm - 只有当输入数据部分发生错误时,Reed-Solomon 错误算法才允许更正?

java - 使用空格时字符串索引越界异常

Java Postgresql 运行时错误

spring-mvc - 错误页面在tomcat中正常工作,但在weblogic中工作不正常

C、用文本文件保存/读取NULL

c - 传递指针时内容错误

c++ - 可以在纯 C++ 中使用指针吗?

javascript - 无法访问全局变量