Reputation: 43
I have a problem with fscanf
, which my structure array will keep both account number and name together in customer[i].Acc_No
, and repeating keep my name in customer[i].fullname
.
First time scanning won't have problem, it start from 2nd time. Why?
Example:
id:FAFB1234 name:LEE FU HUA
customer[0].Acc_No store "FABE1234LEE FU HUA"
My code:
information customers[10];
int i;
FILE *fptr;
fptr=fopen("Customer.txt","r");
file_check(fptr);
i=0;
while(!feof(fptr))
{
fscanf(fptr,"%[^|]|%[^|]|%[^|]|%d %d %d %lf %d %d %d",customers[i].Acc_No,customers[i].fullname,customers[i].address
,&customers[i].birthday.day,&customers[i].birthday.month,&customers[i].birthday.year,&customers[i].balance_owning,&customers[i].last_trans.day
,&customers[i].last_trans.month,&customers[i].last_trans.year);
i++
}
My txt file:
FAFB1234|LEE FU HUA|NO38 JALAN BUNGA TAMAN LAWA 48235 SHAH ALAM,SELANGOR|18 09 1995 0.00 1 9 2014
FEBE2014|LOW CHU TAO|A-111 JALAN YING TAMAN YANGYANG 56981 WANGSA MAJU,KUALA LUMPUR|30 03 1996 0.00 1 9 2014
FAFB2014|JERRY CHOW|I-414 JALAN MATINI TAMAN ASRAMA PENUH 56327 SETAPAK,KUALA LUMPUR|15 02 1995 0.00 1 9 2014
FEBE1001|LEE WEI KIET|NO 49 JALAN 5/6 TAMAN BUNGA SELATAN 48752 HULU SELANGOR,SELANGOR|06 09 1996 0.00 1 9 2014
FAFB1001|HO HUI QI|NO 888 JALAN 65/79 TAMAN TERLALU BESAR 75368 KUANTAN,PAHANG|26 04 1996 0.00 1 9 2014
Upvotes: 1
Views: 85
Reputation: 22552
scanf
and family can have very unpredictable results reading directly from the stream. If a parse failed everything else is bound to fail afterwards.
When using scanf
and family it's always recommended to read your data line by line with fgets
and then sscanf
on the buffer.
Try this:
information customers[10];
FILE *fptr;
fptr=fopen("Customer.txt","r");
file_check(fptr);
// buffer to read line by line
char line[0x1000];
int i = 0;
while (fgets(line, sizeof(line), fptr)) {
information this_customer; // buffer for surrent customer
memset(&this_customer, 0, sizeof(this_customer));
int num_entries_read = sscanf(line,"%[^|]|%[^|]|%[^|]|%d %d %d %lf %d %d %d",this_customer.Acc_No,this_customer.fullname,this_customer.address
,&this_customer.birthday.day,&this_customer.birthday.month,&this_customer.birthday.year,&this_customer.balance_owning,&this_customer.last_trans.day
,&this_customer.last_trans.month,&this_customer.last_trans.year);
if (num_entries_read == 10) { // all fields were successfullt matched
// copy this customer into the array
customers[i] = this_customer;
i++;
} else {
fprintf(stderr, "failed to parse line: %s", line);
}
}
Upvotes: 1