[英]Fscanf in C for storing data from file
Here's my code. 这是我的代码。
#include<stdio.h>
struct element {
int value;
char activity;
};
typedef struct element element;
int main(int argc,char** argv) {
FILE* fp;
fp = fopen(argv[1], "r");
element a;
while(feof(fp) == 0) {
fscanf(fp, "%c %d", &a.activity, &a.value);
printf("\n%d", a.value);
}
}
now,it outputs me every integer on file two time.. 现在,它两次向我输出文件上的每个整数。
Howcome i am getting this weird answer? 我如何得到这个奇怪的答案?
My structure is: 我的结构是:
struct element {
int value;
char activity;
};
typedef struct element element;
and my input file is: 而我的输入文件是:
i 23
i 56
i 19
i 20
i 44
Look at your fscanf
pattern: 看一下你的
fscanf
模式:
fscanf(fp, "%c,%d", &a.activity, &a.value);
Then at your file format: 然后以您的文件格式:
i 23
i 56
i 19
i 20
i 44
I don't see any commas. 我看不到逗号。 Try a space instead, and be sure to take the newline into account:
请尝试使用空格,并确保将换行符考虑在内:
fscanf(fp, "%c %d\n", &a.activity, &a.value);
Remember fscanf
doesn't just read values in order, it respects the fixed characters surrounding the wildcards. 请记住,
fscanf
不仅按顺序读取值,还尊重通配符周围的固定字符。
Edit -- also important, pointed out by Keith in the comments: 编辑-同样重要,Keith在评论中指出:
Note that using
\\n
in thefscanf
format string may be slightly misleading.请注意,在
fscanf
格式字符串中使用\\n
可能会引起误解。 Any white-space character (including\\n
) matches zero or more white-space characters.任何空格字符(包括
\\n
)都与零个或多个空格字符匹配。 So adding the\\n
works for the given input -- but it would also work if the input were all on one line separated by spaces or tabs:i 23 i 56 i 19 i 20 i 44
.因此,添加
\\n
对于给定的输入有效-但如果输入全部都在由空格或制表符分隔的一行上,则也将起作用:i 23 i 56 i 19 i 20 i 44
。 If you really want line-oriented input, usefgets()
(notgets()
) to read a line at a time into a string, thensscanf()
to parse the string.如果您确实需要面向行的输入,请使用
fgets()
(而不是gets()
)一次将一行读入字符串,然后使用sscanf()
解析该字符串。 (All the*scanf()
functions have problems with numeric overflow, though.)(不过,所有
*scanf()
函数都存在数字溢出问题。)
Hope it helps! 希望能帮助到你!
(PS: oh, and I fixed your code formatting. Next time you post, take a second to make sure the code looks properly indented and stuff. Seeing a messy code snippet kinda takes away the desire to answer, you'll get much less feedback in your questions!) (PS:哦,我已经解决了您的代码格式问题。下次您发布代码时,请花一点时间来确保代码看上去正确地缩进并填充内容。看到凌乱的代码段有点带走了回答的欲望,您会得到的好处就更少了反馈您的问题!)
a.activity
is uninitialized until fscanf
returns the first time. 直到
fscanf
第一次返回时,活动a.activity
初始化。 While you are debugging, keep this in mind. 在调试时,请记住这一点。 Most debuggers will put a "cursor" on the first line which has not yet been executed;
大多数调试器会将“游标”放在尚未执行的第一行; therefore, when the
fscanf
line is highlighted the first time, a.activity
will not yet be initialized, and may have any value at all in it. 因此,第一次突出显示
fscanf
行时, a.activity
尚未初始化,并且可能根本没有任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.