类型转换char指针浮在C中 [英] typecasting char pointer to float in C

查看:78
本文介绍了类型转换char指针浮在C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有ff数据的平面文件:

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;
}

我的问题是如何从char *price将价格设置为float(根据结构的要求).我得到的最接近的结果,即没有产生编译器错误的地方是

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.

谢谢!

推荐答案

您正在寻找 strtod strtoul 以外的任何内容来将quantity转换为文本到int,这可能是一个错误(我能想到的唯一例外是,如果出于某些原因quantity可以为负,那么您会希望使用strtol代替).

You are looking for the strtod strtof 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).

这篇关于类型转换char指针浮在C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆