C Program fscanf skips lines

时间:2015-10-30 23:08:08

标签: c file-io struct scanf

This program takes a file and is supposed to transfer the files contents to a struct

The contents of the file is:

11.0,  11.0, 11.0,  14.0
22.4,  22.4, 22.4,  28.9
12.7,  13.8, 14.6,  14.5
23.5,  13.5, 42.5,  21.8
18.0,  16.0, 21.0,  42.9
21.0,  21.0, 21.0,  100.0   

The output of the file is:

22.4,  22.4, 22.4, 28.9
23.5,  13.5, 42.5, 21.8
21.0,  21.0, 21.0, 100.0

It is skipping every other line from the contents of the file and I am not sure how to fix this issue.

#include <stdio.h>

#define MAX_ITEMS 100

struct item {
    double item1;
    double item2;
    double item3;
    double item4;
};

int main(void)
{
    struct item myItems[MAX_ITEMS]; 
    int i = 0;

    FILE *input;
    input = fopen("items.txt", "r");

    if(input == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    while(fscanf(input, " %lf,%lf,%lf,%lf", &myItems[i].item1,&myItems[i].item2,   
             &myItems[i].item3, &myItems[i].item4) == 4) 
    {
       fscanf(input, " %lf,%lf,%lf,%lf", &myItems[i].item1,&myItems[i].item2,    
             &myItems[i].item3, &myItems[i].item4);
       printf("%lf %lf %lf %lf\n", myItems[i].item1, myItems[i].item2,     
             myItems[i].item3, myItems[i].item4);
       i++;
    }

  fclose(input);
  return 0;
}

1 个答案:

答案 0 :(得分:5)

The problem occur because you call fscanf twice and only print the results of the latter. You you instead do this

while(fscanf(input, " %lf,%lf,%lf,%lf", &myItems[i].item1,&myItems[i].item2,   
             &myItems[i].item3, &myItems[i].item4) == 4) {
     printf("%lf %lf %lf %lf\n", myItems[i].item1, myItems[i].item2,     
             myItems[i].item3, myItems[i].item4);
    i++;
}