I don't understand how the output is being obtained. specifically how does this part work fscanf(fptr,"%*[^\n]"); as I've never seen this sort of complexity. Thanks.
I don't understand how the output is being obtained. specifically how does this part work fscanf(fptr,"%*[^\n]"); as I've never seen this sort of complexity. Thanks.
%[abc] means to accept only a, b, and c.
%[^abc] means to accept anything except a, b, and c.
%[^\n] means to accept anything except a newline (i.e., read until a newline)
%*[^\n] means that you are not going to assign the characters to a variable; instead they are thrown away.
So scanf("%*[\n]") means "read up to (but not including) the next newline and throw those characters away".
A little inaccuracy saves tons of explanation. - H.H. Munro
I understand the first fscanf brings the file pointer fptr to the space right before yard. Then the second fscanf brings the file pointer to the end of the file right before the new line and throws everything away. Then we go back to the first fscanf and that is where I dont understand how we can get the second line of output.
Firstly, fptr is a pointer to a struct, not a pointer "into the file" or anything like that. It points to a struct that contains the current file position as one of its members.
The first fscanf would bring the file position to the space before "yard".
Then the "%*[^\n]" would read the space and "yard" but not the newline.
Then the first fscanf runs again. The first format is "%f". The first thing that format does is to skip whitespace. So it skips the newline (and any other spaces) until it encounters a non-whitespace. Then it tries to read that as a floating point number.
A little inaccuracy saves tons of explanation. - H.H. Munro
So then it will try to read "one" as a floating point number and gets 0. Then the next instruction is to get a string, so shouldn't it grab "one" as the next parameter? Why does fscanf not get anything new the second time around? Thanks for all the help.
I'm not sure what you mean by "and gets 0". fscanf will return 0 in that case (so n will be 0). The variable that you wanted the value to be stored into will be unmodified by fscanf if it couldn't read a number. So it will have it's last value.
About your question, as soon as fscanf fails, it stops scanning and returns the number of fields it successfully read. So that fscanf call would return the value 0, which is not equal to EOF (which is guaranteed to be negative), so the loop continues. Generally that's not what you want and if this was real code you might want to ensure you actually read all 4 fields before continuing.
A little inaccuracy saves tons of explanation. - H.H. Munro
THANKS!! I didn't know that it would return 0 if it did not find a number when it was looking for one. This whole thing makes sense now.