2

I need to read from a text file and store its points in a int array. That part I've sucessfully done with FILE* fp = fopen( filename, "r" ). Using fscanf (fp, "%f", &n); to read from the file. My file structure type is like the following (I'm storing information to build a graph btw):

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

I need to store the following:

  • Male Female in a char array (as many as nr of point rows)
  • 2003 ... 2011 in another char array (as many as points columns)
  • 1 array for each row of points.

So far I have accomplished the 3rd point using fscanf (fp, "%f", &n), but I need help on how to alternate the reading from chars to ints. Is this possible to do, or do I have to split files into legend.txt and points.txt ?

EDIT: All information is not fixed-size. The logic is:

  • first line nr rows / nr columns
  • second line is y legend
  • third line is x legend
  • next lines are random, with nr columns as max
4

1 回答 1

0

你可以尝试这样的事情:

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]);
于 2013-04-30T17:30:39.427 回答