Rick
Rick

Reputation: 21

fscanf reads twice a line

I'm using fscanf in a text file like this:

T 1 1000
T 2 700
N 3 450
Y 4 200

I'm trying to count the lines to use a malloc and to do that I use:

Prize temp;
int count =0;
while ((fscanf(fa,"%c %d %f", &temp.A, &temp.B, &temp.C))!= EOF)
count ++;

where Prize is a struct:

typedef struct {
  char A;
  int B;
  float C;
} Prize;

So, after reading the lines the program prints me this:

 A: T B: 1 C: 1000.0000
 A:   B: 0 C: 0.0000
 A: T B: 2 C: 700.0000
 A:   B: 0 C: 0.0000
 A: N B: 3 C: 450.0000
 A:   B: 0 C: 0.0000
 A: Y B: 4 C: 200.0000

Using the debugger I noticed that fscanf gets (for example while reading the first line):

A = 84 'T', B=1, C=1000

and instead of reading the second line it reads another first line, but like this:

A = 10'\n', B=1, C=1000

and continues doing this for each line but the last.

I controlled the file and it doesn't have extra spaces or lines.

Any suggestions to solve the problem?

Upvotes: 0

Views: 1042

Answers (2)

user31264
user31264

Reputation: 6727

Your file contains newlines. So the sequence of characters in the file is really as following:

T 1 1000\nT 2 700\n...

The first fscanf reads 'T', 1, and 1000. It stops at the '\n' character.

The seconds fscanf reads the '\n' character to temp.A. Now it is at the second 'T' character. Therefore, it is unable to read temp.B and temp.C

The third fscanf reads 'T', 2, and 700, but stops at '\n' again.

You should skip all whitespace characters before reading temp.A, which is done by the space in the format string:

...fscanf(fa," %c %d %f", &temp.A, &temp.B, &temp.C)...

Upvotes: 1

lulyon
lulyon

Reputation: 7225

The %c format of the reading would not ignore any space or \n character, even which it is unseen. However %s %d %c will. It is likely the better way to avoid the inconsistency if replace %c by %s(and single character to be a string).

char str[maxn];
fscanf(fa, "%s%d%f", str, &temp.B, &temp.C);
temp.A = str[0];

Upvotes: 0

Related Questions