首页 > 解决方案 > 读取具有动态整数大小的二维数组并垂直输出

问题描述

我试图让用户在这样的一个输入中输入所有整数值,直到 EOF:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

然后垂直输出它们:

1 6 11
2 7 12
3 8 13
4 9 14
5 10 15

我尝试了不同的方法,但始终无法正确读取输入。

int numberArray[][100] = {0};  
char tempChar;

while (scanf("%d%c", &numberArray[i][j], &tempChar) != EOF) {
    j++;
    if (tempChar != '\n') {
        i++;
        j = 0;
    }
}

for (int k = 0; k < i; k++) {
    int arraySize = sizeof(numberArray[k]) / sizeof(numberArray[k][0]);
    for (int f = 0; f < arraySize; f++) {
        printf("%d ", numberArray[k][f]);
    }
}

标签: carrays

解决方案


我创建了这样的东西,它仅适用于每行中相同数量的列。我认为这就是您想要实现的目标。此外,如果你想真正基于动态内存来做,你应该使用它mallocrealloc因为现在数组大小是预定义的(在我的情况下最大 5x5)

#include <stdio.h>
#include <string.h>


int main(void)
{
        int arr[5][5],j,i,columns,rows;
        char x,end[10]; //end takes input after enter so it can get next value thats why its string
        for (i = 0, j = 0;; i++, j = 1) {
            if (j != 0) arr[i][0] = atoi(end);
            do {
                scanf("%d%c", &arr[i][j], &x);
                j++;

            } while (x != '\n');
            scanf("%s", end); //if u want to end input use x I could do it to next enter but I run into some dificulties and I got no time.
            if (strcmp("x",end)==0) {
                i++;
                rows = j;
                break;
            }
        }

        columns = i;
        for (j = 0; j < rows; j++) {
            for (i = 0; i < columns; i++) {
                printf("%d ", arr[i][j]);
            }
            printf("\n");
        }
    return 0;
}

推荐阅读