对于我的任务,用户输入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
我不是真的确定如何解决它,所以任何帮助表示赞赏。
'i'在哪里初始化? – Marievi
哎呦我的坏,忘了把它,它是初始化虽然 – Raze
我不能再现你的问题......我运行的代码,它等待,直到它得到5个元素。 – Marievi