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.
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
.
mknpokok
is an array of 20
menuinput
so use the subscript operator on that, mknpokok[i]
. while(!feof(stream))
and then try to read from the stream without checking that reading succeeded. See Why is “while(?feof(file) )” always wrong?%.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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.