首页 > 解决方案 > 从文件中扫描数据并传递给结构

问题描述

我正在尝试从文件中获取数据并将其存储在结构中。我使用一个名为的字符串buffer来获取所有文本,然后我使用一个名为的字符串one_line将数据传递给结构。

我在代码注释中添加了一些解释。

#include<stdlib.h>
#include<stdio.h>
#define N 10000
#define line 30
typedef struct player
{
    char full_name[N];
    int year[N];
    char team_name[N];
} player;

void main()
{
    char buffer[1000];//string to store all data from afile
    char one_line[line];//string for a struct that take each line separate
    player p[500];//array of struct
    FILE *ptr;//pointer to file
    int i=0,count_of_player=0;
    ptr=fopen("player of the year.txt","r");
    if(ptr==NULL)
    {
        printf("cant open ");
        return;
    }
    while (fgets(buffer,N,ptr)!=NULL)//the buffer get all the text
    {
        while (one_line!='\0')//the string get one line in a time 
        {
            fscanf(ptr,"%d %s %s",&(p[i].year),&(p[i].full_name),&(p[i].team_name));\\get date from file to struct
            i++;
            count_of_player++;
        }
    }
    fclose(ptr);
    while (buffer!=NULL)
    {
        printf("%s",buffer);
    }
    for (i=0;i<count_of_player;i++)
    {
        printf("%s won the best player trophy in %d at the team:%s",p[i].full_name,p[i].year,p[i].team_name);
    }
}

标签: c

解决方案


推荐阅读