Here’s my code.
#include<stdio.h>
struct element {
int value;
char activity;
};
typedef struct element element;
int main(int argc,char** argv) {
FILE* fp;
fp = fopen(argv[1], "r");
element a;
while(feof(fp) == 0) {
fscanf(fp, "%c %d", &a.activity, &a.value);
printf("\n%d", a.value);
}
}
now,it outputs me every integer on file two time..
Howcome i am getting this weird answer?
My structure is:
struct element {
int value;
char activity;
};
typedef struct element element;
and my input file is:
i 23
i 56
i 19
i 20
i 44
Look at your
fscanfpattern:Then at your file format:
I don’t see any commas. Try a space instead, and be sure to take the newline into account:
Remember
fscanfdoesn’t just read values in order, it respects the fixed characters surrounding the wildcards.Edit — also important, pointed out by Keith in the comments:
Hope it helps!
(PS: oh, and I fixed your code formatting. Next time you post, take a second to make sure the code looks properly indented and stuff. Seeing a messy code snippet kinda takes away the desire to answer, you’ll get much less feedback in your questions!)