file io - C Program fscanf skips lines -
this program takes file , supposed transfer files contents struct
the contents of 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 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 skipping every other line contents of file , not sure how fix 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 = 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; }
the problem occur because call fscanf
twice , print results of latter. you instead 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++; }
Comments
Post a Comment