[英]C Program fscanf skips lines
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;
}
The problem occur because you call fscanf
twice and only print the results of the latter. 发生此问题的原因是您两次调用
fscanf
并仅打印后者的结果。 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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.