2017-08-14 24 views
-1

我試圖從文件中獲取多個元素,並將其放入我的數組鏈表中,但它只輸入文件的最後一個元素。C編程,fscanf只輸入最後一個元素

文件裏面是

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

這裏是我的代碼

typedef struct node{ 
    int elem; 
    struct node *next; 
}node; 

void insert(node **a) 
{ 
    int temp,elem; 
    node *tempstruct; 
    tempstruct = (*node)malloc(sizeof(struct node)); 
    FILE *fp; 
    if(fp = fopen("input.txt","r")){ 
     while(fscanf(fp,"%d",&elem)==1){ 
      temp = elem%10; 
      tempstruct->elem = elem; 
      tempstruct->next = a[temp]; 
      a[temp] = tempstruct; 
     } 
    } 
} 

預期的輸出應該

A[0] 10 
A[1] 11 1 
A[2] 12 2 
A[3] 13 3 
A[4] 14 4 
A[5] 15 5 
A[6] 16 6 
A[7] 17 7 
A[8] 18 8 
A[9] 19 9 

但我得到的是

A[0] 19 
A[1] 19 
A[2] 19 
A[3] 19 
A[4] 19 
A[5] 19 
A[6] 19 
A[7] 19 
A[8] 19 
A[9] 19 

我試圖把對應於自己的個位數字索引元素,但所有的這把是是19

+6

您的代碼無法編譯。例如'(* node)','temp =%elem;' – BLUEPIXY

+0

儘量避免類型轉換malloc的返回值。 –

+0

你正試圖調試太多。首先,瞭解如何從文件中讀取數據。第二,弄清楚如何將這些項目分配給節點的 – KevinDTimm

回答

2

你只叫malloc一個時間,讓你最終的情況是,所有的最後一個元素數組中的元素指向同一個對象。相反,您應該爲每個成功的掃描調用malloc

像:

void insert(node **a) 
{ 
    int temp,elem; 
    node *tempstruct; 
    FILE *fp; 
    if(fp = fopen("input.txt","r")){ 
     while(fscanf(fp,"%d",&elem)==1){ 
      tempstruct = malloc(sizeof(struct node)); // malloc inside the loop 
      temp = elem % 10;  // Find the index where the new object shall be added 
      tempstruct->elem = elem; 
      tempstruct->next = a[temp]; 
      a[temp] = tempstruct; 
     } 
    } 
} 
+0

代碼是不穩定的:目前還不清楚a [] '是有效的。 – chux

+0

@chux真。不幸的是,OP從未發佈完整的代碼示例。然而,從「預期輸出」看,假設'a []'有10個元素,即10個鏈表,其中數據根據最後一位數據排序,這似乎是公平的。 – 4386427

相關問題