I am trying to write a program that reads from a file, and adds the information into an array of structures.
File looks something like this:
Berlin;1500
Dublin;1200
Paris;1600
However, I get junk as an output.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct covidInfo{
char cityName[20];
int casesNo;
};
int main()
{
struct covidInfo *cities = (struct covidInfo*)malloc(3*sizeof(struct covidInfo));
FILE *fl = fopen("CovidCasesByCity.txt","rb");
if (fl == NULL)
{
printf("File cannot be opened.\n");
return 0;
}
char c;
int i = 0,j = 0;
for (c = getc(fl) ; c != EOF ; c = getc(fl))
{
if (((c > 64) && (c < 91)) || ((c > 96) && (c < 123)))
{
cities[i].cityName[j] = c;
j++;
}
if (c == ';')
{
j=0;
}
if ((c > 48) && (c < 58))
{
int num = fscanf(fl,"%1d",&cities[i].casesNo);
}
if (c == '\n')
{
i++;
}
}
for (i = 0 ; i < 3 ; i++)
printf("%s %d\n",cities[i].cityName,cities[i].casesNo);
}