3

我有一个包含 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;
}

我的问题是如何floatchar *price. 我得到的最接近的,即没有产生编译器错误的是

 e.price = *(float *)price

但这会导致分段错误。

谢谢!

4

3 回答 3

4

您正在寻找strtod strtof库函数(包括<stdlib.h>)。相关地,如果调用代码使用除了从 textstrtoul转换为 之外的任何东西,那可能是一个错误(我能想到的唯一例外是,如果由于某种原因可能是负面的,那么你会想要)。quantityintquantitystrtol

于 2013-09-09T13:29:43.457 回答
1

要将文本转换为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;
}

顺便说一句:建议进行额外的更改以将目标记录传递到您的初始化中,但这会进入更高级别的体系结构。

于 2013-09-09T13:48:06.887 回答
0

您遇到分段错误,因为 afloat有 4 个字节:当您*(float *)price访问价格的前 4 个字节时,如果价格的大小小于 4 个字符,您将遇到错误。

我认为你能做的最好的事情就是在解析数据时读取 afloat而不是 a char *(就像我假设你对数量所做的那样),例如fscanf (pFile, "%s;%d;%f;%s", &date, &quantity, &price, &item);

或使用strtod转换为floatin而不是进行强制转换。initialize

于 2013-09-09T13:42:21.637 回答