This question already has an answer here:
- How to convert string to float? 8 answers
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
strtod
strtof
library function (include<stdlib.h>
). Relatedly, if the calling code uses anything other thanstrtoul
to convertquantity
from text to anint
, that is probably a bug (the only exception I can think of would be, if for some reasonquantity
can be negative, then you would wantstrtol
instead).You are having a segmentation fault because a
float
have 4 Bytes: when you make*(float *)price
you are accesing to the first 4 Bytes of price, so if price´s size is smaller than 4 chars, you will have an error.I think that the best you can do is read a
float
instead achar *
when you parse the data (as i supose yo do with quantity), for examplefscanf (pFile, "%s;%d;%f;%s", &date, &quantity, &price, &item);
or convert to
float
ininitialize
with strtod instead of make a cast.To convert text to a
float
, usestrtof()
.strtod()
is better fordouble
.Your initialize routine likely wants a copy of the `date, etc.
A suggested improved routine follows:
BTW: Recommend an additional change to pass into your initialization the destination record, but that gets into higher level architecture.