Using fscanf to read an integer from a file

gcc 4.4.4 c89

I have the following file which contains name, age and gender. I try to read at this age.

"Bloggs, Joe" 34 M

I can successfully open the file:

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

And I try to read at the age of (34).

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

However, when I try to print the result, I always get zero by age and result.

Thanks so much for any suggestions,

+3
source share
2 answers

You did nothing to skip this name, so it looks at this text, trying to convert it to int and fails, so the return value is 0 (0 conversions succeeded) and the value that was in the variable remains unchanged. You need to add the code to skip the name and then view the age:

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

"%c" . "%[^\"]\" ( ) . "*" , , . , "% d".

+11

- . , fscanf.

int ch=0;
while(((ch=fgetc(stream)))!=EOF && !isdigit(ch)){}
ungetc(ch,stream);
+1

Source: https://habr.com/ru/post/1757385/


All Articles