I have a flat file with the ff data:
date;quantity;price;item
I want create a data record using the following struct:
typedef struct {
char * date, * item;
int quantity;
float price, total;
} expense_record;
I created the following initializing method:
expense_record initialize(char * date, int quantity, char *price, char *item) {
expense_record e;
e.date = date;
e.quantity = quantity;
e.item = item;
/* set price */
return e;
}
My question is how to set the price as float (as required by the struct) from the char *price. The closest I got, i.e. without generating a compiler error was
e.price = *(float *)price
but this results in segmentation faults.
Thanks!
You are looking for the strtodstrtof library function (include <stdlib.h>). Relatedly, if the calling code uses anything other than strtoul to convert quantity from text to an int, that is probably a bug (the only exception I can think of would be, if for some reason quantity can be negative, then you would want strtol instead).
To convert text to a float, use strtof(). strtod() is better for double.
Your initialize routine likely wants a copy of the `date, etc.
A suggested improved routine follows:
expense_record initialize(const char * date, int quantity, const char *price, const char *item) {
expense_record e;
char *endptr;
e.date = strdup(date);
e.quantity = quantity;
e.item = strdup(item);
if (!e.date || !e.item) {
; // handle out-of -memory
}
e.price = strtof(price, &endptr);
if (*endptr) {
; // handle price syntax error
}
return e;
}
BTW: Recommend an additional change to pass into your initialization the destination record, but that gets into higher level architecture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With