嗨,我正在尝试将文件中的数据读取到结构数组中,我尝试使用fgets,但出现错误,提示无法将RECORD类型转换为char *,这是我到目前为止所拥有的

#include <stdio.h>
#include <stdlib.h>

#define MAX_NAME   20
#define FILE_NAME  50
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)


typedef struct RECORD
{
    char *name;
    float  score;
}RECORD;


int main (void)
{
    // Declarations
       FILE *fp;
       char fileName[FILE_NAME];
       RECORD list[LIST_SIZE];
       int count = 0;
    // Statements
       printf("Enter the file name: ");
       gets(fileName);

       fp = fopen(fileName, "r");

       if(fp == NULL)
           printf("Error cannot open the file!\n");
         while (fgets(list[count], LIST_SIZE, fp) != NULL)
         {
             count++;
         }
       return 0;
}


错误在while循环内的fgets语句中发生,如何解决此问题并将数据读入结构数组?

预先感谢

最佳答案

fgets用于从文本文件中以一行为单位输入字符串。

例如。)

char input_line_buff[128];
fgets(input_line_buff, 128, fp);


读入

input_line_buff :(内容例如)“名称66.6 \ n”

您可以进行split,内存分配和复制以及convert。

例如。)

list[count].name = strdup("name");
list[count].score= atof("66.6");
count++;

关于c - 从文件读取数据到结构数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15985010/

10-11 04:07
查看更多