我試圖將.txt文件存儲到struct中,但未成功。 我不需要存儲第一行,但我確實需要其餘的。 謝謝你們! =)將.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
而你的闕stion /錯誤是? – ckruczek
你的'fscanf'預計身高和體重的整數,但他們顯然是floatin數字。難怪 – Aif
,但結構仍然不存儲在txt正確的數據 –