Reputation: 77
I'm using AT commands for a program I'm making and am having trouble parsing them using the sscanf() function.
For instance, if I take this command:
"AT\r\r\nOK\r\n"
I want to: * On the first call, get only the "AT" part, throw away the following "\r" character and know how many characters have been read up to that point. * On the second call, get only the "OK" part, throw away the "\r\n" characters that come before and after the "OK" string and know how many characters have been read up to that point.
I wrote the following sscanf function call:
index = 0;
sscanf(buffer + index, "%*[\r\n]%[^\r]\r%*[\n]%n", new_buffer, &count);
index += count;
Why won't it return the strings I requested? What am I doing wrong?
Thank you in advance for your help.
Upvotes: 3
Views: 882
Reputation: 183978
Let's analyse the format:
sscanf(buffer + index, "%*[\r\n]%[^\r]\r%*[\n]%n", new_buffer, &count);
First, an initial sequence of '\r'
or '\n'
characters are skipped (%*[\r\n]
). Then the following characters until the next '\r'
are scanned and stored into new_buffer
(%[^\r]
).
Next, all following whitespace characters are skipped (\r
). The part up to the 'O'
of "OK"
has been consumed now.
Then, all characters until the next newline are ignored (%*[^\n]
). You are now left with only the final newline not consumed. Then the number of consumed characters is stored in count
.
Your problem is that any whitespace in a format string (outside character sets, of course) consumes the entire sequence (possibly empty) of whitespace characters appearing in that place. The \r
in the format string does not mean "one character '\r'
", it means "all whitespace here".
You could fix it (if your format is rigid) by making it scan (and ignore) any character (which in your case is guaranteed to be a '\r'
if your input is really what you expect.
sscanf(buffer + index, "%*[\r\n]%[^\r]%*c%*[\n]%n", new_buffer, &count);
Upvotes: 0
Reputation: 72746
Maybe the problem is how sscanf
deals with white space characters, such as carriage return and newline, and your expectations. sscanf
is required to ignore (skip) preceding white space.
Another problem might be that the carriage returns never make it to your buffer. C implementations are required to map \r\n
to \n
on input (for text streams).
Upvotes: 1