我正在尝试创建一个程序来从文件中读取二维数组,然后将其打印出来。
文件的设置使得第一行有行数,然后是列数。之后绘制数组。示例如下:
3 5
10.4 15.1 18.5 13.3 20.8
76.5 55.3 94.0 48.5 60.3
2.4 4.6 3.5 4.6 8.9
我的问题是我只知道如何使用 fgets 和 sscanf 读取每行的第一个元素,因此忽略了后面的数字。
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]){
FILE* f = fopen("plottestdata", "r");
char size[20];
int height, width,ii=0,cc,jj,kk;
float array[100][100];
char horiz[500];
if(fgets(size, 20, f)!= NULL){
sscanf(size,"%d %d", &height, &width);
printf("%d %d\n",height, width);
}
while(fgets(horiz, 500, f)!=NULL)
{
if(ii<height)
{
for(cc=0;cc<width;cc++)
{
sscanf(horiz, "%f", &array[ii][cc]);
}
ii++;
}
}
for(jj=0;jj<width;jj++)
{
for(kk=0;kk<height;kk++)
{
printf("%f ", array[jj][kk]);
}
}
fclose(f);
return 0;
}
这给了我重复多次的每一行的第一个元素的输出,我明白为什么但不确定如何修复它。它正在读取的文件实际上是一个 20x20 数组,尽管其格式与示例相同。
此外,为了缩短一个长问题,我省略了错误检查。
最佳答案
我忍不住调整和简化您的代码,它是如此接近,以避免使用 fgets
并使用 fscanf
直接读取值。加上基本的错误检查。
#include <stdio.h>
#include <stdlib.h>
#define MWIDTH 100
#define MHEIGHT 100
int main(void){
FILE* f;
int height, width, ii, jj;
float array[MHEIGHT][MWIDTH];
if((f = fopen("plottestdata.txt", "r")) == NULL)
exit(1);
if(fscanf(f, "%d%d", &height, &width) != 2)
exit(1);
if (height < 1 || height > MHEIGHT || width < 1 || width > MWIDTH)
exit(1);
for(jj=0; jj<height; jj++)
for(ii=0; ii<width; ii++)
if(fscanf(f, "%f", &array[jj][ii]) != 1)
exit(1);
fclose(f);
for(jj=0; jj<height; jj++){
for(ii=0; ii<width; ii++)
printf ("%10.1f", array[jj][ii]);
printf("\n");
}
return 0;
}
程序输出:
10.4 15.1 18.5 13.3 20.8
76.5 55.3 94.0 48.5 60.3
2.4 4.6 3.5 4.6 8.9
关于c - 从 C 文件中读取二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998105/