将数据从csv文件读取到struct中,并返回错误 [英] Reading data from csv file into struct, getting errors back

查看:118
本文介绍了将数据从csv文件读取到struct中,并返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将csv文件中的数据读取到结构中.该结构包含int,char和float成员.除char成员外,我得到了其他错误.我对C很陌生,因此感谢您的帮助!

I'm trying to read data from a csv file into a struct. The struct contains int, char and float members. I'm getting errors back except for the char member. I'm fairly new to C so I appreciate your help!

csv文件订单"中的数据:

Data from csv file "Order":

0, cafe, 3.90, 0
0, espresso, 3.50, 0
...

我的结构:

typedef struct {                       
 int   position;
 char  name[20];
 float price;
 int   counter;
}drink;

void init(drink *pt)
{
 FILE *fp;
 char buf[50];
 int i = 0, j;
 fp=fopen("Order", "r");
 while( fgets(buf,sizeof(buf),fp) != NULL)
 {
    strcpy(pt[i].position, strtok(buf,","));
    strcpy(pt[i].name, strtok(NULL,","));
    strcpy(pt[i].price, strtok(NULL,","));
    strcpy(pt[i].counter, strtok(NULL,","));
    ++i;
 }
}

int main()
{
  int number = NR;
  int d=0;
  drink bar[number];          
  drink *pt = &bar[0];

  welcome();
  init(pt);
  ...
  return 0;
 }

推荐答案

  1. 错误的副本.

请勿使用strcpy()将字符串复制到int.而是将其转换.

Do not use strcpy() to copy a string to an int. Rather convert it.

// strcpy(pt[i].position, strtok(buf,","));
char *endptr;
pt[i].position = strtol(strtok(buf,","), &endptr, 10);
// or 
pt[i].position = atoi(strtok(buf,","));
...
pt[i].price = strtod(strtok(NULL,","), &endptr);

(注意:省略了各种错误检查)

(Note: Various error checking omitted)

  1. 启用所有编译器警告.这将节省您的时间,因为您的编译器应该已经抓住了这一点.
  2. 如果遇到错误,编译时或运行时,请发布错误 而不是将错误描述为找回错误".
  1. Enable all compiler warnings. This will save you time as your compiler should have caught this.
  2. If you were getting errors, compile time or run time, post the error rather than weakly describe the error as "getting errors back".

这篇关于将数据从csv文件读取到struct中,并返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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