fscanf在读取char时不能在C中工​​作#

时间:2014-01-15 01:21:00

标签: c string file char scanf

我必须阅读一些与#和\ n分开的足球比赛的文本文件。 我试过这个:

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);
}

但是当它到达时会崩溃:

    f=fscanf(ul,"%[^#]#",dr);
是的,有人能帮帮我吗? 我使用fscanf错了吗?

输入文件是这样的:

Carlton Blues (Melbourne)#Geelong Cats (Geelong)#3:0
Collingwood Magpies (Melbourne)#Melbourne Demons (Melbourne)#5:3

......等等......

2 个答案:

答案 0 :(得分:0)

你没有为pr和dr分配任何空间。 scanf需要将数据读取到缓冲区。

这是C++ Reference for fscanf

的示例
/* 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;
}

答案 1 :(得分:0)

Preet就是现场。

另外如果你觉得在循环之外有一个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);
}

将打印

pr-Carlton Blues (Melbourne)
dr-Geelong Cats (Geelong)
re-3:0
pr-Collingwood Magpies (Melbourne)
dr-Melbourne Demons (Melbourne)
re-5:3
相关问题