我需要从文本文件中读取并将其点存储在一个 int 数组中。我已经使用 FILE* fp = fopen( filename, "r")
成功完成了这一部分。使用 fscanf (fp, "%f", &n);
从文件中读取。我的文件结构类型如下(顺便说一句,我正在存储信息以构建图表):
5 9
Male Female
2003 2004 2005 2006 2007 2008 2009 2010 2011
306.414 319.601 360.589 357.510 375.473 374.654 387.245 391.020 391.540
70.051 82.289 94.062 91.496 108.617 114.345 125.313 127.948 131.628
我需要存储以下内容:
- 一个字符数组中的男性女性(与点行一样多)
- 2003 ... 2011 在另一个字符数组中(与点列一样多)
- 每行点 1 个数组。
到目前为止,我已经使用 fscanf (fp, "%f", &n)
完成了第 3 点,但我需要有关如何将读取从字符转换为整数的帮助。这是可能的,还是我必须将文件拆分为 legend.txt 和 points.txt?
编辑:所有信息都不是固定大小的。逻辑是:
- 第一行 nr 行/nr 列
- 第二行是y图例
- 第三行是x图例
- 下一行是随机的,nr列为最大值
最佳答案
你可以尝试这样的事情:
int nrows, ncols;
fscanf(fp, "%d", &nrows);
nrows-=3;
fscanf(fp, "%d", &ncols);
int i,j;
// Heap allocation. Be careful, you might need more
// space than it is available on the heap
char row_legend[nrows][SIZE];
char col_legend[ncols][SIZE];
float values[nrows][ncols];
for(i = 0; i < nrows; ++i)
fscanf(fp, "%s", row_legend[i]);
for(i = 0; i < ncols; ++i)
fscanf(fp, "%s", col_legend[i]);
for(i = 0; i < nrows; ++i)
for(j = 0; j < ncols; ++j)
fscanf(fp, "%f", &values[i][j]);
关于C 从文件中读取多个数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305149/