开发者

C Programing fscanf

I've a file that contain this:

JS;John Silver;27264543

and I want to get the info separately, like this:

Name: John Silver

Code: JS

Telephone: 27264543

I'm using this:

while(!eof(fp2))
{
    fread(line, 1, 100,fp2);
    fscanf(fp2,"%s;%[^;]s,%[^;]d",p.code, p.name, p.tel);    
}
printf(开发者_运维问答"Code: %s\n", p.code);
printf("Name: %s\n",p.name);
printf("Telephone: %d\n",p.tel);

p is the struct;

But is not working, it is crashing. What I'm doing wrong?

Regards


If p.tel is an int, then you need to pass a pointer to it into fscanf. Try &p.tel as the parameter instead.

(However, this is just a guess, because we don't have the definition of the type of p.)


You need to check the return value of scanf(), not just assume it worked.

if (fscanf(fp,"%s;%[^;]s,%[^;]d",p.code, p.name, p.tel) != 3) /* handle error */;

Hint: Your example line returns 2 from the scanf. The scanf fails at the literal s

"%s;%[^;]s,%[^;]d"
/*  HERE ^ */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜