//flex table opened by JP

Click to See Complete Forum and Search --> : C fscanf() not reading right!


bassman
05-19-2003, 03:47 PM
Aloha! I'm getting an error while using fscanf - I use it to read a file that contains many data on a line, but I only need the first two parts of it, a string and an integer; so the syntax I'm using is fscanf(fp,"%s %d\n", name, &number);
Problem is, it keeps on reading to the end of the line, instead of changing line after reading the integer! What's wrong with this?

Here's the file; the **** thing reads the date and part of the time info :( :mad: :confused:

word 2 19-05-2002 14:30:31
word 4 19-05-2002 14:30:35
word 2 19-05-2002 14:30:37
pepsi 2 19-05-2002 14:30:39
pepsi 3 19-05-2002 14:30:42

nothing
05-19-2003, 11:15 PM
Not that I don't like the SysOpt forums but people here seem to know more about hardware than programming languages. That's why I will suggest you this forum (http://www.blackcode.com/forums/viewforum.php?f=11 ). Just copy and paste your post over there and you'll get answers really fast.

bassman
05-21-2003, 03:47 PM
You're right about one thing; programming isn't quite our strength, but we're working on improving it...However, as said in our AUP:
"You will not post advertisements..."

bassman
05-21-2003, 03:53 PM
So, the clever me ignored that fscanf reads the whole line and sort of binds the format string passed as it's second argument to the variable names passed on as third...So if you use * in the second argument, fscanf won't assign the rest of the values to any variables. Something like this (untested) could be done to get only a string and an integer:

fscanf(fp,"%s %d *", string, &number);

But I like to be different (and dunce :rolleyes: ) so I did it this way:

fscanf(fp,"%s %d *", string, &number);
fgets(trash,sizeof(trash),fp); /*the rest of the line gets trashed*/

nothing
05-21-2003, 09:19 PM
What did you mean by this?

"You will not post advertisements..."

frnkzks
05-22-2003, 01:38 PM
Or you could read the rest of the line, and discard it.

while(...)
{
fscanf(fp,"%s %d *", string, &number);
for(i=0; i < count; i++)
fscanf(fp,"%s", string);
}

bassman
05-24-2003, 04:45 PM
Originally posted by nothing
What did you mean by this?

"You will not post advertisements..."
Read this:
http://www.internet.com/corporate/privacy/aup.html

nothing
05-26-2003, 12:28 PM
:rolleyes:

rick42
05-26-2003, 09:34 PM
fscanf just reads the tokens you tell it, staying or skipping lines.
If you always want to read the first N tokens on each line, but don't know the rest of the line, use fgets to scan in a line from the file, then use sscanf to extract the first 2 tokens from the buffer from fgets.
:t