简体   繁体   English

fscanf读取两次行

[英]fscanf reads twice a line

I'm using fscanf in a text file like this: 我在这样的文本文件中使用fscanf:

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: 我试图计算使用malloc的行数,并使用以下代码:

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): 使用调试器,我注意到fscanf得到了(例如,在读取第一行时):

A = 84 'T', B=1, C=1000 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 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? 有解决问题的建议吗?

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 . 第一个fscanf读取'T'11000 It stops at the '\\n' character. 它停在'\\n'字符处。

The seconds fscanf reads the '\\n' character to temp.A . fscanf秒数将'\\n'字符读取到temp.A Now it is at the second 'T' character. 现在是第二个“ T”字符。 Therefore, it is unable to read temp.B and temp.C 因此,它无法读取temp.Btemp.C

The third fscanf reads 'T' , 2 , and 700 , but stops at '\\n' again. 第三个fscanf读取'T'2700 ,但再次在'\\n'处停止。

You should skip all whitespace characters before reading temp.A , which is done by the space in the format string: 在读取temp.A之前,您应该跳过所有空格字符,这由格式字符串中的空格完成:

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

The %c format of the reading would not ignore any space or \\n character, even which it is unseen. 读数的%c格式不会忽略任何space\\n字符,即使看不见也是如此。 However %s %d %c will. 但是%s %d %c会。 It is likely the better way to avoid the inconsistency if replace %c by %s (and single character to be a string). 如果将%c替换为%s (并且单个字符为字符串),则可能是避免不一致的更好的方法。

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

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

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