Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to input a data file into a 2D array
    primarykey
    data
    text
    <p>I've got a file which I need to store in a 2-D array so I can perform matrix operations on it. All I know is that the doubles will be separated by spaces and line breaks, e.g:</p> <pre><code>2.04 3.0 4.0 5.0 6.1 7.0 8.0 9.03 10.0 </code></pre> <p>I won't know how many numbers there will be, so I need a scalable parsing function. So far I have:</p> <pre><code>int main(int argc, char* argv[]) { FILE *fp; char ch; fp = fopen("matrix.dat","r"); if ( fp == NULL ) { puts ( "Cannot open source file"); } /*count the number of lines*/ int lines=1; char c; while((c = fgetc(fp)) != EOF) { if(c == '\n') lines++; } printf("lines= %i\n",lines); /*reopen the file to reset the pointer*/ fclose(fp); fp = fopen("matrix.dat","r"); double m[lines][lines]; /*Load file into array*/ int i,j; for(i=0;i&lt;lines;i++) { for(j=0;j&lt;lines;j++) { fscanf( fp, "%lf", &amp;(m[i][j])); } fscanf(fp, "\n", NULL); } /*print out stored matrix*/ for(i=0;i&lt;lines;i++) { for(j=0;j&lt;lines;j++) { printf("%lf ",m[i][j]); } printf("\n"); } } </code></pre> <p>My issues with this method are </p> <ol> <li><p>It makes the assumption that the number of rows equals the number of doubles per line, which may not be true.**</p></li> <li><p>Any missing doubles in the file will cause the program to load the wrong matrix into memory (remaining values offset by 1).</p></li> <li><p>I'm currently loading the file into memory twice to count the lines. </p></li> </ol> <p>Is there a more sensible way to input this data into a 2D array? I need to ensure that the input matrix is square and that my program can handle a square matrix of any order. I'm quite new to C, so examples and naming functions will be much appreciated :) (Apologies for the dodgy indenting)</p> <p>** Sorry for being so vague, I wanted some error handling, i.e making sure the input is not accepted unless there are exactly nxn doubles.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload