简体   繁体   English

将特定格式的文本文件读取到c中的2d数组/矩阵中

[英]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. 我正在尝试将特定格式的文本文件读取为2d数组,但是我认为我做的不正确。 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. while循环及其中的所有内容都会计算文本文件中的行数,因此我将矩阵设置为文件中的行数。

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. 这是一个邻接表,因此第一行表示边权重为2的节点2和边权重为6的节点4与节点1(文本文件的第一行)相邻,依此类推。

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. 似乎您正在学习C,这是您的作业,因此最好自己解决。 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. 停止在学习C中使用Turbo C / C ++,因为它已经过时并且目前不满足编码要求。

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. rewind(fp)-在打开文件后不需要,但是在到达文件末尾到达文件顶部时才需要。 Thus, the rewind(fp) would be as under: 因此,rewind(fp)将如下所示:

     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: 现在读取值并填充2D数组,如下所示:

      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++; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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