2015-02-06 102 views
0

我在C中遇到了struct的問題,任何人都可以幫忙嗎?我是C新手,所以請對我好。我已經在下面聲明瞭兩個結構,其中一個嵌套在另一個結構中。從文件初始化嵌套結構的值

struct orders_tag { 
    int number_of_orders; 
    char item_name[20]; 
    int price; 
}; 

typedef struct orders_tag order; 

struct customer_tag { 
    char name[30]; 
    order total_order[10]; 
}; 

typedef struct customer_tag customer; 

我也在main中初始化了這些值。

customer cus_array[20]; 
customer c; 

我想從文件中讀取信息,並把這些值代入我的嵌套的結構,但我真的不明白是怎麼回事。任何解釋將不勝感激。

infile = fopen("input.txt", "r"); 

if (infile == NULL) { 
    printf("Couldn't open the fire."); 
    return 1; 
} 

while (fscanf(infile, "%s %d %s %2f", c.name, c.total_order.number_of_orders 
     , c.total_order.item_name, c.total_order.price) != EOF) { 

} 

我相信我得到的唯一錯誤是來自while循環條件。

+0

'total_order'是一個數組。所以這個'c.total_order.item_name'和這個'c.total_order.price'不會被編譯。 – alk 2015-02-06 09:19:26

+0

謝謝,我會認爲我會做一些本地臨時變量,並將文件中的值放入這些臨時變量中,然後從那裏手動初始化該結構。 – ln206 2015-02-06 09:21:50

回答

2

在您的代碼中,price定義爲int,並且您正在使用%2f來讀取該值。不正確。

只是爲了參考,章節7.19.6.2,第10段,C99標準,

除非分配抑制是由*指示的,轉換的結果被放置在該對象指向的第一個參數以下 格式參數尚未收到轉換結果。如果此對象沒有適當的類型,或者轉換的結果無法在對象中表示,則行爲是未定義的。

接下來,與fscanf(),你應該提供存儲位置的指針,其中值必須存儲。您需要根據需要使用&

此外,在c.total_order.number_of_orders的情況下,total_order是一個數組,因此您必須使用數組下標來表示數組中的特定變量。像

c.total_order[i].number_of_orders 

其中i被用作索引。

+1

看看totalorder是一個數組。它也有問題 – Gopi 2015-02-06 09:21:33

+0

@gopi謝謝。只是在更新。 :-) – 2015-02-06 09:22:36

+0

@戈皮謝謝先生。在'fscanf()'中也解決了這個問題:-) – 2015-02-06 09:25:01

0

在customer_tag結構中,您將total_order聲明爲數組,您應該在掃描值時引用每個元素。此外,&在的fscanf整型值之前需要

while (fscanf(infile, "%s %d %s %2f", c.name, &(c.total_order[0].number_of_orders) 
     , c.total_order[0].item_name, &(c.total_order[0].price)) != EOF) {} 

只是也許有某種增量來改變total_order陣列的哪些元素,您正在訪問

0
int i=0; 
while (fscanf(infile, "%s %d %s %d", &c.name,&c.total_order[i].number_of_orders 
     , &c.total_order[i].item_name, &c.total_order[i].price) == 4) { 
i++; 
} 

剛上添加代碼如何讀取結構的值。