0

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);
}
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • Strings are supposed to be terminated with `\0` character. But you are explicitly filtering these out. – Eugene Sh. Oct 29 '20 at 15:45
  • Thank you! This solved the problem with the junk in my output. But I still can't get the casesNo correctly from the file. – hediye tapan Oct 29 '20 at 15:49
  • Don't cast the result of malloc, please. https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – DarkAtom Oct 29 '20 at 16:36
  • Rather than using raw ASCII codes, use the character literals: `c >= 'A'` instead of `c > 64` etc. – DarkAtom Oct 29 '20 at 16:38

0 Answers0