Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using fscanf to read in a integer from a file

Tags:

c

gcc 4.4.4 c89

I have the following file that contains name, age, and gender. I am trying to read in the age.

"Bloggs, Joe" 34 M

I can open the file successfully:

fp = fopen("input.txt", "r");
if(fp == NULL) {
    fprintf(stderr, "Failed to open file [ %s ]\n", strerror(errno));
    return 1;
}

And I try and read in the age ( 34 ).

int age = 0;
int result = 0;
result = fscanf(fp, "%d", &age);

However, when I try and print the outcome, I always get a zero for age and result.

Many thanks for any suggestions,

like image 607
ant2009 Avatar asked Jul 30 '10 16:07

ant2009


1 Answers

You've done nothing to skip across the name, so it's looking at that text, attempting to convert it to an int and failing, so the return value is 0 (0 conversions succeeded) and the value that was in the variable remains unchanged. You need to add code to skip across the name, then read the age:

fscanf(fp, "%*c%*[^\"]\" %d", &age);

The initial "%c" reads the initial quote. The "%[^\"]\" reads characters up to (and including) the next quote. In both cases, the "*" means that value will be read but not stored anywhere. After that, we can read the number using the "%d".

like image 184
Jerry Coffin Avatar answered Sep 25 '22 18:09

Jerry Coffin