繁体   English   中英

使用fscanf进行文件扫描

[英]File scanning with fscanf

我在fscanf遇到问题,我的结构数组会将帐号和名称都存储在customer[i].Acc_No ,然后重复将我的名字存储在customer[i].fullname 第一次扫描没有问题,它从第二次开始。 为什么?

例:

id:FAFB1234 name:LEE FU HUA

customer[0].Acc_No store "FABE1234LEE FU HUA"

我的代码:

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++
}

我的txt文件:

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

scanf和family可能会直接从流中读取结果,结果非常不可预测。 如果解析失败,那么其他所有注定会失败。

使用scanf和family时,始终建议先与fgets逐行读取数据,然后在缓冲区上读取sscanf

尝试这个:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM