【发布时间】:2016-06-18 00:50:59
【问题描述】:
以下代码从文件中获取输入并将其存储在一维数组中。我想要一个矩阵类型的输入,例如:
1,2,4
3,4,5
5,6,7
(或)
2,3,4,5
4,5,6,7
7,6,5,4
3,4,5,6
矩阵的大小不同,它们用逗号分隔,存储在二维数组中。我应该对以下代码进行哪些更改?
#include <stdio.h>
#include <stdlib.h>
int main(){
char file[51];
int data, row, col, c, count, inc;
int *array, capacity=50;
char ch;
array = (int*)malloc(sizeof(int) * capacity);
printf("\nEnter the name of the file with its extention\n");
scanf("%s", file);
FILE *fp = fopen(file, "r");
row = col = c = count = 0;
while (EOF != (inc = fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
++c; //COLUMN count
if (capacity == count)
array = (int*)realloc(array, sizeof(int) * (capacity *= 2));
array[count++] = data;
if(ch == '\n'){
++row;
if (col == 0){
col = c;
} else if (col != c){
fprintf(stderr, "format error of different Column of Row at %d\n", row);
goto exit;
}
c = 0;
} else if (ch != ',') {
fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
goto exit;
}
}
{ //check print
int i, j;
//int (*matrix)[col] = array;
for(i = 0; i < row; ++i){
for(j = 0; j < col; ++j)
printf("%d ", array[i * col + j]);//matrix[i][j]
printf("\n");
}
}
exit:
fclose(fp);
free(array);
return 0;
}
【问题讨论】:
-
要做的更改之一:向内存分配和文件打开添加错误检查。
-
谢谢你。注意到变化。
-
goto指令应始终通过使用条件来避免。 -
@Olaf 是的,我知道。但是,由于
goto可能很容易出错,因此如果不是 100% 必要,则不应使用它。通常它不是并且可以避免。例如。在这种情况下,还可以编写一个函数cleanup(FILE* fp, int* array)来释放分配的内存并关闭文件。
标签: c arrays algorithm multidimensional-array