1755616 Members
3472 Online
108836 Solutions
New Discussion юеВ

fscanf is broken?

 
SOLVED
Go to solution
Mary Rice
Frequent Advisor

fscanf is broken?

Hello Experts,

I'm having a problem with fscanf in a program written in ESQL/C. It reads data which has been formatted by an awk program for input into an Informix database.

Each line of data looks like this:
Account Number Date Amount Name Description
412-99-3412 08/01/2002 5.75 "Mary Rice" "Pencils and Paper"
541-45-8911 08/02/2002 121.90 "Robert Rice" "Copier Toner"

I am using an fscanf function like this

n = fscanf(infile,"%s %s %lf %s %s\n",account_no,date,&amount,name,description);

All the variable types are correct. The first three variables work perfectly but Name = ""Robert" and Description = "Rice"". What am i doing wrong?

Please don't ask to man scanf; I've done that!!!

Thanks for your help,
Mary
2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: fscanf is broken?

Mary:

You need to man scanf and look for the %[ section. The problem is thatr %s stops ate the first whitespace; it knows nothing about your quotes. Since you mentioned that the data is being pre-massaged by awk I would throw the quotes away and choose a better field delimter than a space character. My typical choice is a .

Your data should then look like this:
412-99-341208/01/20025.75Mary RicePencils and Paper

Now change your fscanf to look like this:
n = fscanf(infile,"%s\t%s\t%lf\t%[^\t\n]\t%[^\t\r\n",account_no,date,&amount,name,description);

Note the %[^\t\n] that means keep scanning until you see a TAB or LF and load the string with that pattern. I left the earlier fields as %s because they seem to not have whitespace.

That should fix you, Clay


If it ain't broke, I can fix that.
Mary Rice
Frequent Advisor

Re: fscanf is broken?

Thanks Clay! As usual a truly "magical" answer. I changed the printfs in my awk program to use tabs and now I don't need the quotes at all.

Thanks,
Mary