我需要从文件中读取数据,但无法从中读取整个值

时间:2014-04-24 18:33:57

标签: c file-io text-parsing

1 (0.000000,0.000000)   1  429
2 (0.000000,0.000000)   4  58 346 373 465
3 (0.000000,0.000000)   5  94 293 381 431 481
4 (0.000000,0.000000)   3  27 363 458
5 (0.000000,0.000000)   1  471
6 (0.000000,0.000000)   1  79
7 (0.000000,0.000000)   3  111 254 297
8 (0.000000,0.000000)   3  257 425 432
9 (0.000000,0.000000)   2  195 357
10 (0.000000,0.000000)   2  24 95

这是我尝试从名为xyz.txt的文件中读取的数据类型 所以我写了一些代码,但仍然无法正确读取文件,因为每一行都有离散格式的数据。

#include<conio.h>
#include<stdio.h>

int main() 

{
    FILE *fp;


    struct net 
    { 

      int id,pc;
      float h,w; 
      int a[10];

    }n;



    fp = fopen("xyz.txt","r+");

        if(fp == NULL)
       {
              printf("Error in opening file");
              exit();
       }
       while(fscanf(fp,"%d   (%f ,%f)  %d\n",&n.id,&n.h,&n.w,&n.pc)!=EOF)
     printf("%d (%f ,%f) %d\n",n.id,n.h,n.w,n.pc);


    fclose(fp);
    getch();
     return 0;

}

2 个答案:

答案 0 :(得分:1)

由于您没有使用fscanf消耗整行,因此剩余的值会使您的扫描失败。使用fgets读取整行,然后使用sscanf扫描,或者将%*[^\n]添加到fscanf的末尾(读取字符,直到遇到换行符) ,由于星号,忽略这些字符。)

此外,您应该根据预期字段的数量测试fscanf的返回值,在您的情况下为4。

while (fscanf(fp,"%d   (%f ,%f)  %d%*[^\n]", &n.id, &n.h, &n.w, &n.pc) == 4)
    printf("%d (%f ,%f) %d\n", n.id, n.h, n.w, n.pc);

答案 1 :(得分:1)

while(fscanf(fp, "%d (%f,%f) %d",&n.id,&n.h,&n.w,&n.pc)!=EOF){
    int i;
    for(i=0;i<n.pc;++i){
        fscanf(fp, "%d", &n.a[i]);
    }
    printf("%d (%f, %f) %d\n",n.id,n.h,n.w,n.pc);
}