[英]Reading a specifically formatted text file into a 2d array/matrix in c
我正在嘗試將特定格式的文本文件讀取為2d數組,但是我認為我做的不正確。 這是我到目前為止的內容:
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]);
}
}
}
while循環及其中的所有內容都會計算文本文件中的行數,因此我將矩陣設置為文件中的行數。
這是我的文字檔
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
這是一個鄰接表,因此第一行表示邊權重為2的節點2和邊權重為6的節點4與節點1(文本文件的第一行)相鄰,依此類推。
我的問題是,我不知道如何將文本文件中的信息放入矩陣中。 任何建議都會有所幫助!
給您一些建議:
似乎您正在學習C,這是您的作業,因此最好自己解決。 因為每項作業都有一定的目的
停止在學習C中使用Turbo C / C ++,因為它已經過時並且目前不滿足編碼要求。
許多錯誤
rewind(fp)-在打開文件后不需要,但是在到達文件末尾到達文件頂部時才需要。 因此,rewind(fp)將如下所示:
fp = fopen ("file.txt", "r"); while(!feof(fp)){ ch = fgetc(fp); if (ch == '\\n') lines++; } rewind(fp);
現在讀取值並填充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.