c - 读取具有动态整数大小的二维数组并垂直输出
问题描述
我试图让用户在这样的一个输入中输入所有整数值,直到 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]);
}
}
解决方案
我创建了这样的东西,它仅适用于每行中相同数量的列。我认为这就是您想要实现的目标。此外,如果你想真正基于动态内存来做,你应该使用它malloc
,realloc
因为现在数组大小是预定义的(在我的情况下最大 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;
}
推荐阅读
- python - 如何根据其他列中的值对 Pandas 中的值进行排序?
- python - CFG 中的 NLTK python 变量
- javascript - 我正在尝试创建一个名为 user args 的频道。[DISCORD.JS V12]
- vue.js - Vue中绑定到数据属性的div的动画宽度
- unity3d - Handheld.PlayFullScreenMovie 方法没有返回按钮
- javascript - 如何在javascript中克隆主文档dom?
- c++ - 成员默认构造函数的必要性
- swift - UITableViewController loadView 用故事板中的标识符实例化了视图控制器,但没有得到 UITableView
- java - 为什么这个竞态条件的输出有些一致?
- python - Python 网页抓取,仅收集 80% 到 90% 的预期数据行。我的循环有问题吗?