[英]fscanf not working in C while reading char #
I have to read text file with some football matches seperated with # and \\n. 我必须阅读带有#和\\ n分开的一些足球比赛的文本文件。 I tried this:
我尝试了这个:
char *pr;
char *dr;
char *re;
int f;
ul=fopen("nogomet.txt","r");
f=fscanf(ul,"%[^#]#",pr);
while (f!=EOF){
printf("pr-%s\n",pr);
f=fscanf(ul,"%[^#]#",dr);
printf("dr-%s\n",dr);
f=fscanf(ul,"%[^\n]\n",re);
printf("re-%s\n",re);
f=fscanf(ul,"%[^#]#",pr);
}
But it chrashes when it gets at: 但是到达时它会崩溃:
f=fscanf(ul,"%[^#]#",dr);
Can someone help me please? 有人能帮助我吗? Am I using fscanf wrong?
我使用fscanf错误吗?
input file is like this: 输入文件是这样的:
Carlton Blues (Melbourne)#Geelong Cats (Geelong)#3:0
Collingwood Magpies (Melbourne)#Melbourne Demons (Melbourne)#5:3
...and so on... ...等等...
You've not allocated any space for pr and dr. 您尚未为pr和dr分配任何空间。 The scanf needs to read data to a buffer.
scanf需要将数据读取到缓冲区。
here's an example from the C++ Reference for fscanf 这是fscanf的C ++参考中的示例
/* fscanf example */
#include <stdio.h>
int main ()
{
char str [80]; // << ---------- allocated some space.
float f;
FILE * pFile;
pFile = fopen ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "PI");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str); // <<--------------------
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}
Preet is spot on. Preet在现场。
Also if you feel a bit uneasy about having one fscanf() outside of the loop, you can do this: 另外,如果对循环外有一个fscanf()感到不安,可以执行以下操作:
char pr[500];
char dr[500];
char re[500];
int f;
while (1){
//PR
f=fscanf(ul,"%[^#]#",pr);
if (f==EOF)
break;
printf("pr-%s\n",pr);
//DR
f=fscanf(ul,"%[^#]#",dr);
//we can also check f here
printf("dr-%s\n",dr);
//RE
f=fscanf(ul,"%[^\n]\n",re);
//we can also check f here
printf("re-%s\n",re);
}
will print 将打印
pr-Carlton Blues (Melbourne)
dr-Geelong Cats (Geelong)
re-3:0
pr-Collingwood Magpies (Melbourne)
dr-Melbourne Demons (Melbourne)
re-5:3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.