【发布时间】:2015-03-01 22:51:36
【问题描述】:
我在读取文本文件时遇到问题,使用该信息形成一个二维数组,该数组将打印为一个矩阵。
具有这些值的文本文件:
4
9 12 13 1
7 3 6 9
8 4 2 1
10 5 15 3
第一个整数 (4) 将用于确定二维数组的行和列,例如。
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) 读取第一个值以确定二维数组的维度
2) 转到下一行
3) 将下一个值逐一读取并存入数组
4) 打印出来。
我该怎么做呢?
感谢您的阅读。
【问题讨论】: