I have a string with multiple lines and I want to use sscanf to match particular parts of it. It only seems to work however on matching data contained within the first line.
For example, If I have the string:
“age1: x \r\n
age2: x”
And using sscanf:
sscanf(string, “age1: %d”, &i); – this works
sscanf(string, “age2: %d”, &j); – however this doesn’t.
Any ideas?
As others have stated,
sscanfdoesn’t remember how much data was read and advance the input data likescanfandfscanfdo. Use the%nspecifier to remember how much data was read, and advance the input yourself:The
%nspecifier says “tell me how many bytes of input have been read up to this point, and store it in the next argument (which must be a pointer to anint)”. By putting it at the end of the format string, we can figure out how much input was parsed. Also note that I added a newline after the%dso that we eat the whitespace after the first integer; otherwise when we attempted to read"age 2", it would see a newline next instead of the charactera, and parsing would fail because that’s not a match.