Home > front end >  file scan using fscanf with array struct in c
file scan using fscanf with array struct in c

Time:06-18

So i wanna know how to use fscanf with array struct. So this is my struct

struct menuinput{
        char nama[50];
        int nomor;
        int berat;
        int jumlah;
        int pilihan;
        float kalori;
        float totalkkal;
    }mknpokok[20],mknsayur[20],mknspsj[20],mknlaukpauk[20],mknbuah[20];

And i wanna use it in file scan using fscanf, as far as i know file scan command is like this

while(!feof(fp))    
{
        fscanf(fp,"\n%d %[^\n] %d %.3f",&mknpokok.nomor[i],mknpokok.nama[i],&mknpokok.berat[i],&mknpokok.kalori[i])
        i  ;
}

When i run that i get this error message

error: '(struct menuinput *)&mknpokok' is a pointer; did you mean to use '->'?

I forget how to fscanf with array struct, so is what am i doing is correct? if wrong please correct it with the right code, thank you.

CodePudding user response:

You are accessing the elements of the struct mknpokok in a wrong way.

You should access them like &mknpokok[i].nomor instead of &mknpokok.nomor[i], since you have declared array of mknpokok, not nomor.

CodePudding user response:

  • You have placed the subscript operator on the wrong elements. mknpokok is an array of 20 menuinput so use the subscript operator on that, mknpokok[i].
  • Never use while(!feof(stream)) and then try to read from the stream without checking that reading succeeded. See Why is “while( !feof(file) )” always wrong?
  • You should always make sure that you don't read more elements than you can fit in your array. Always do bounds checking.
  • %.3f is not a standard conversion. You should probably use %f.

Example:

//   only populate elements 0-19
//              v
    while (i < 20 && fscanf(fp, " %d %[^\n] %d %f", &mknpokok[i].nomor,
                            mknpokok[i].nama, &mknpokok[i].berat,
                            &mknpokok[i].kalori) == 4) {
//                                               ^^^^
//                                    check that fscanf succeeded
          i;
    }
  • Related