简体   繁体   中英

Reading a specifically formatted text file into a 2d array/matrix in c

I'm trying to read a specifically formatted text file into a 2d array however I don't think I am doing it right. This is what I have so far:

int main()
{
   int start;
   int end;
   int ch = 0;
   int lines = 0;
   int i;
   int j;

   FILE *fp;
   fp = fopen ("file.txt", "r");
   rewind(fp);
   while(!feof(fp))
   {
       ch = fgetc(fp);
       if (ch == '\n')
       lines++;
   }

   int graph[lines][lines];
   memset(graph, 0, sizeof lines);

   //I don't think I'm doing the matrix populating correct. PLEASE HELP!
   for (i = 0; i < lines; i++)
   {
       for (j = 0; j < lines; j++)
       {
           int node;
           int edge;
           fscanf(fp, "%d,%d", &graph[&node][&edge]);
       }
   }
}

The while loop and everything in it counts how many lines there are in the text file and the so I set the matrix to the number of lines there are in the file.

This is my text file

2,2 4,6
1,2 3,3 4,8 5,5
2,3 5,7
1,6 2,8 5,9
2,5 3,7 4,9

This is an adjacency list so the first line means node 2 with edge weight 2 and node 4 with edge weight 6 are adjacent to node 1 (first line of text file) so on and so forth.

My problem is, is that I don't know how to put the information from the text file into a matrix. Any advice would help!

some advices for you:

  • Seems that you are learning C and this is your assignment thus would better in futher you solve these own your own. As there is some purpose in every assignment

  • Stop using Turbo C/C++ in Learning C as it is old fashion and currently doesn't meet the coding requirements.

Many Errors

  1. rewind(fp) - is not required after you opened the file but required when you reache the end of the file to reach at top of the file. Thus, the rewind(fp) would be as under:

     fp = fopen ("file.txt", "r"); while(!feof(fp)){ ch = fgetc(fp); if (ch == '\\n') lines++; } rewind(fp); 
  2. Now Reading the values and filling the 2D array as under:

      while (!feof(fp)) { int node; int edge; char c; int lineno=0; fscanf(fp, "%d,%d%c", &node, &edge, &c); graph[node][edge]=lineno; if ( c == '\\n' ){ lineno++; } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM