Kraken
Kraken

Reputation: 24223

Fscanf in C for storing data from file

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

Upvotes: 1

Views: 1444

Answers (2)

salezica
salezica

Reputation: 77029

Look at your fscanf pattern:

fscanf(fp, "%c,%d", &a.activity, &a.value);

Then at your file format:

i 23
i 56
i 19
i 20
i 44

I don't see any commas. Try a space instead, and be sure to take the newline into account:

fscanf(fp, "%c %d\n", &a.activity, &a.value);

Remember fscanf doesn't just read values in order, it respects the fixed characters surrounding the wildcards.

Edit -- also important, pointed out by Keith in the comments:

Note that using \n in the fscanf format string may be slightly misleading. Any white-space character (including \n) matches zero or more white-space characters. So adding the \n works for the given input -- but it would also work if the input were all on one line separated by spaces or tabs: i 23 i 56 i 19 i 20 i 44. If you really want line-oriented input, use fgets() (not gets()) to read a line at a time into a string, then sscanf() to parse the string. (All the *scanf() functions have problems with numeric overflow, though.)

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!)

Upvotes: 2

Daniel Wagner
Daniel Wagner

Reputation: 153102

a.activity is uninitialized until fscanf returns the first time. While you are debugging, keep this in mind. Most debuggers will put a "cursor" on the first line which has not yet been executed; therefore, when the fscanf line is highlighted the first time, a.activity will not yet be initialized, and may have any value at all in it.

Upvotes: -1

Related Questions