首页 > 解决方案 > 处理非法数组

问题描述

一些上下文:这个程序读取 Stone 的行并将它们放到地图上。

程序应该首先询问 STONE 的行数作为整数。然后,程序会将行的位置扫描为一组四个整数,格式如下:

行列长度值

行和列表示要放置在地图上的水平线块中最左边的块。长度告诉你在这条水平线上应该有多少石头。在此示例中,假设第四个整数始终为 1,表示石头。

示例:命令含义

0 0 5 1 放置一条石头线,从 [0][0] 开始,到 [0][4] 结束。该行中的所有 5 个方格都将设置为 1 (STONE)。

注意:前三个整数(行列长度)可能导致部分或全部在地图之外的行。如果是这种情况,您应该完全忽略此行,不要对地图进行任何更改。

因此问题:当我输入非法数组值时,例如 22 22 22 1,它会简单地停止程序并说出现错误。我如何让程序简单地忽略该命令行并继续其余部分,就好像它从未输入过一样?

#define SIZE 15
#define EMPTY 0
#define STONE 1

void printMap(int map[SIZE][SIZE], int playerX);

int main (void) {
    // This line creates our 2D array called "map" and sets all
    // of the blocks in the map to EMPTY.
    int map[SIZE][SIZE] = {EMPTY};

    int playerX = SIZE / 2;

    printf("How many lines of stone? ");
    int linesOfStone; 
    scanf("%d", &linesOfStone);

    printf("Enter lines of stone:\n");
  
    int rowPos; 
    int columnPos; 
    int stoneLength; 
    int stoneValue; 
   
    int i = 0; 
    while (i < linesOfStone) {
        scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue); 

//ERROR ERROR this is where i attempt to fix tackle the problem but my logic seems lost... 
        if (rowPos < 0 || columnPos < 0) {
        rowPos = 0; 
        columnPos = 0; 
        map[0][0] = 0; 
        } else if (rowPos > SIZE || columnPos > SIZE) {
        rowPos = 0; 
        columnPos = 0; 
        map[0][0] = 0; 
        } else {
        map[rowPos][columnPos] = stoneValue; 
        }
        
            int j = 0; 
            while (j < stoneLength) { 
            map[rowPos][columnPos + j] = 1; 
            j++; 
            }
    i++; 
    }


    printMap(map, playerX);

    return 0;
}


void printMap(int map[SIZE][SIZE], int playerX) {
    
    // Print values from the map array.
    int i = 0;
    while (i < SIZE) {
        int j = 0;
        while (j < SIZE) {
            printf("%d ", map[i][j]);
            j++;
        }
        printf("\n");
        i++;
    }    
    
    // Print the player line.
    i = 0;
    while (i < playerX) {
        printf("  ");
        i++;
    }
    printf("P\n");
}

标签: arrayscwhile-loop

解决方案


减一

rowPos > SIZE应该rowPos >= SIZE。对columnPos > SIZE.

建议进行额外的测试以确保在stoneLength.

没有范围限制stoneLength

范围限制最佳应用独立性

//if (rowPos < 0 || columnPos < 0) {
if (rowPos < 0) {

推荐阅读