类型转换char指针在C中浮动
我有一个包含ff数据的平面文件:
date;quantity;price;item
我想使用以下结构创建数据记录:
typedef struct { char * date, * item; int quantity; float price, total; } expense_record;
我创建了以下初始化方法:
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; }
我的问题是如何从char *price
将价格设置为float
(根据结构的要求)。 我得到的最接近,即没有产生编译错误
e.price = *(float *)price
但这会导致分段错误。
谢谢!
你正在寻找 strtod
strtof
库函数(包括
)。 相关地,如果调用代码使用strtoul
以外的任何东西将quantity
从文本转换为int
,那可能是一个bug(我能想到的唯一例外是,如果由于某种原因quantity
可能是负数,那么你会想要strtol
代替)。
要将文本转换为float
,请使用strtof()
。 strtod()
更适合double
。
您的初始化例程可能需要副本 “日期等”。
建议的改进程序如下:
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; }
顺便说一句:建议进行额外的更改以将初始化传递到目标记录,但这会进入更高级别的体系结构。
你有一个分段错误,因为float
有4个字节:当你进行*(float *)price
你正在访问前4个字节的价格,所以如果价格大小小于4个字符,你就会出错。
我认为你可以做的最好的事情就是在解析数据时读取一个float
而不是一个char *
(因为我对数量有所了解),例如fscanf (pFile, "%s;%d;%f;%s", &date, &quantity, &price, &item);
或者在使用strtod initialize
时转换为float
而不是make。