c - 从文件中扫描数据并传递给结构
问题描述
我正在尝试从文件中获取数据并将其存储在结构中。我使用一个名为的字符串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++ - 按值捕获 lambda 中的变量, const_cast 它和 std::move 它 - 未定义的行为?
- python - Python Pandas:如何仅对几列中的数据进行平均 >1000?
- javascript - 我如何知道 JS 中的第二行位置?
- css - Tailwind css悬停不改变文本颜色
- docker - Docker命令行页面历史记录不适用于python:3.7.6-buster
- javascript - 以编程方式单击反应组件
- blockchain - 在测试网 BSC 上部署 SafeMoon 的分叉时出现问题
- unity3d - 当反射强度 > 0 时,Quest 2 上的着色器为白色
- javascript - 在 JavaScript 中使用对象和数组
- elasticsearch - Elasticsearch .NET DocumentExists() 返回错误:从 HEAD 上的不成功 (200) 低级别调用构建的无效 NEST 响应