gpt4 book ai didi

c - 将 .txt 文件存储到结构中

转载 作者:行者123 更新时间:2023-11-30 19:39:04 27 4
gpt4 key购买 nike

我正在尝试将 .txt 文件存储到结构中,但没有成功。我不需要存储第一行,但我确实需要其余的。多谢你们 !! =)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");

struct candidates
{
char name[25];
char gender[5];
int height;
int weight;
};

struct candidates values[25];

FILE *fp;
if ((fp=fopen("candidatesdata.txt","r"))==NULL){printf("Unable to open file\n");}


int x = 0;
int iterations = 0;
while((fscanf(fp,"%s,%s,%d,%d",&values[x].name, &values[x].gender, &values[x].height, &values[x].weight))!=EOF)
{
x++;
iterations +=1;
}
fclose(fp);

//values[15].weight = 300;

printf("\n%d\t%d",iterations,values[1].height);


return 0;
}

文本文件如下所示:

Name,Gender,Height,Weight
Tanner,M,71.8,180.25
John,M,70.75,185.3
Parker,F,65.25,120.3
Meeks,M,57.25,210.2

最佳答案

struct candidates
{
char name[25];
char gender[5]; // can be char gender too !!
int height; // should be changed to float height
int weight; // should be changed to float height
};

如果您实际上有:

Name,Gender,Height,Weight

在你的文件中,你可以在进入 while 循环之前执行他的操作:

char somebigstring[100];
.
.
.
if(fscanf(fp,"%s",somebigstring) == EOF) //wasting the first line
exit(-1); // exiting here if there is no first line

关于c - 将 .txt 文件存储到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com