After reading through other examples here on stack overflow, i'm confused as to where i'm going wrong with my code. I'm trying to read the file and store the 3 pieces of information from each line as data in a struct
e.g. (startTown endTown energyExpended) would be (York Hull 60) for the first line
and then this would be stored in the array allTowns[1024]
any help would be really appreciated, thank you :)
This is the text file i'm trying to read into the struct
This is a link to what the code looks like (is only a few lines)
here is a post in plain text of my code:
struct intertownEnergy {
char startTown[256];
char endTown[256];
int energyExpended;
}
allTowns[1024];
int openEnergyFile(void) {
FILE * energyFilePtr = fopen("energy.txt", "r");
int i = 0;
if (energyFilePtr == NULL) {
printf("no such file.");
return 0;
}
while (!feof(energyFilePtr)) {
fscanf(energyFilePtr, "%s,%s,%d\n", & allTowns[].startTown, & allTowns[].endTown, & allTowns[].energyExpended);
printf("energy test for each line: %d\n", allTowns.energyExpended);
}
return 0;
}
here is the text file:
York Hull 60 Leeds Doncaster -47 Liverpool Nottingham 161 Manchester Sheffield 61 Reading Oxford -43 Oxford Birmingham 103 Birmingham Leicester 63 Liverpool Blackpool 79 Carlisle Newcastle 92
SOLUTION People in the comments helped me to identify the solution to my problem, so I have edited the code and am posting the correct running code below:
struct intertownEnergy{
char startTown[256];
char endTown[256];
int energyExpended;
} allTowns[1024];
int openEnergyFile(void)
{
FILE* energyFilePtr = fopen("energy.txt","r");
int i = 0;
if (energyFilePtr==NULL){
printf("the file doesn't exist");
return 0;
}
while(!feof(energyFilePtr)){
fscanf(energyFilePtr,"%s%s%d\n", &allTowns[i].startTown, &allTowns[i].endTown, &allTowns[i].energyExpended);
printf("energy test for each line: %d\n", allTowns[i].energyExpended);
i++;
}
return 0;
}