[英]Reading in a text file with 5 lines to be filled into a 2D array in C
我在读取文本文件时遇到了问题,使用该信息形成一个2D数组,该数组将打印为矩阵。
具有以下值的文本文件:
4
9 12 13 1
7 3 6 9
8 4 2 1
10 5 15 3
第一个整数(4)将用于确定2D数组的行和列,例如。
int row = 4;
int col = 4;
int matrix[row][col]; //will be a 4x4 matrix
如何使用代码的第一行(值:4)获取数组的尺寸,然后将其余值存储到数组中?
我试图做这样的事情:
#define ARRAYSIZE 10000
char *matDimen;
char *tokenArray;
char buffer[ARRAYSIZE];
FILE *file = fopen("textfile.txt", "r");
while (fgets(buffer, sizeof buffer, file) != NULL)
{
if (row == 0) //Take the first value read to determine the dimension of the array
{
matDimen = strtok(buffer, " "); //Using strtok to read in the first value as a string
row = atol(matDimen); //Converting the string into an int
col = row; //Because rows and columns are going to be the same, initialize column to row
if (row < 1 || 10 < row)
{
if (col < 1 || 10 < row)
{
printf("Matrix must be within 2x2 and 9x9.\n");
exit(0);
}
}
}
for (i = 0; i < row; i++) //Ideally, assigns values from the text file into an index of the array
{
for (j = 0; j < col; j++)
{
tokenArray = strtok(NULL, " ");
//strcpy(matrix[i][j], tokenArray); Program crashes here
//printf("%s ", matrix[i][j]);
}
if (j == col) //Formats the matrix into a 4x4 square, in this scenario
{
printf("\n");
}
}
fclose(file);
我想要的是:
1)读取第一个值以确定2D数组的维数
2)转到下一行
3)逐一读取下一个值并将其存储到数组中
4)打印出来。
我该怎么做呢?
感谢您的阅读。
数组基本上是指向一堆值的指针,因此请考虑int类型的数组arr:
arr[0];
是一样的东西
*arr;
和
arr[2];
是相同的
*(arr+2);
因此,如果您有一个int的2D数组,则实际上您有一个指向int类型的指针的指针。 然后,使用malloc()可以使数组的大小动态:(假设我们将行数读取到称为“行”的var中)
int** arr = malloc(sizeof(int[4])*rows);
arr现在是一个指向4个整数的数组的指针,可以照常访问它:
arr[row][col]
希望能为您解决问题,有关更多信息,请使用Google“动态2d数组c” :)
您可以一次做一件事情,而不是一个循环
fgets(buf, sizeof buf, file);
if (!buf) printf("error 1...\n");
row = atoi( buf );
if ( row < 1 || row > 10 || col < 1 || col > 10 ) printf("error 2...\n");
int r = 0;
while (fgets(buf, sizeof buf, file) )
{
char *p = strtok( buf, " " );
for (int column = 0; column < row; column++)
{
if (!p) break;//error
matrix[r][column] = atoi(p);
p = strtok (NULL, " ");
}
r++;
}
如前一个答案中所述,数组也存在问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.