I'm having trouble with struct in C, could anyone help? I'm new to C and structure so please be kind to me. I have declared two structs below and one of them is nested inside another.
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;
I have initialized these values in main as well.
customer cus_array[20];
customer c;
I'm trying to read the information from the file and put those values into my nested structs but I really don't understand what is going on here. Any explanations would be appreciated.
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) {
}
I believe the only errors I got is from the while loop condition.
In your code, price
is defined as int
and you're using %2f
to read the value. Not correct.
Just for reference, chapter 7.19.6.2, paragraph 10, C99
standard,
Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result.If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
Next, with fscanf()
, you're supposed to supply the pointers of the memory locations where the value has to be stored. You need to use &
as required.
Also, in c.total_order.number_of_orders
case(s), total_order
is an array, so you've to use the array subscript to denote to a particular variable in the array. something like
c.total_order[i].number_of_orders
where i
is used as index.