Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sscanf with multiline string

Tags:

c

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?

like image 679
user496081 Avatar asked Jun 03 '26 20:06

user496081


1 Answers

As others have stated, sscanf doesn't remember how much data was read and advance the input data like scanf and fscanf do. Use the %n specifier to remember how much data was read, and advance the input yourself:

int bytesRead;
if(sscanf(string, "age 1: %d\n%n", &i, &bytesRead) == 1) &&
   sscanf(string + bytesRead, "age 2: %d", &j) == 1)
{
    // success
}
else
{
    // parsing failed
}

The %n specifier 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 an int)". 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 %d so 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 character a, and parsing would fail because that's not a match.

like image 122
Adam Rosenfield Avatar answered Jun 06 '26 09:06

Adam Rosenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!