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,
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With