04-01-2011 08:58 AM
Hi, I'm seeing some odd behavior with the Scan function. Here's some code (for the Interactive Execution) window that demonstrates what I'm struggling with:
#include <formatio.h> static double value;// 1234567890123456
static char buffer[20] = "- 24.612 g ?"; static int scanneditems; static unsigned char sign, stable; static char unit[6]; scanneditems = Scan(buffer, "%s>%c[u]%f%c[d]%s[w5y]%c[u]", &sign, &value, unit, &stable);
The buffer I'm trying to scan has five parts. The first character is a sign, the next 8 characters is a float value, then there is a space which I just discard, then the next five characters is a string describing the unit, and the last character is a question mark if the reading is unstable or a space otherwise. The problem is with the last character. When I run the code above, the value in the variable "stable" is 32 (space), when I'm expecting a 63 (question mark). The other items seem to scan correctly, including the double value and the char array "unit" which contains [g][space][space][space][space] which is exactly what I expect it to contain.
It seems I'm missing something obvious, probably something to do with how the Scan function handles spaces, but I can't figure out what it is. Thanks.
Solved! Go to Solution.
04-01-2011 10:01 AM
I'm not so sure about it how Scan treat spaces, but if you check NumFmtdBytes () after the scan you see 12, which means it has scanned only the "g" (filling the rest of 'unit' with spaces depending on the y modifier) and has read the character immediately following as the stability.
This line correctly reads the entire string and returns 16 bytes scanned by the function, which is what is expected.
scanneditems = Scan (buffer, "%s>%c[u]%f%c[d]%s[w5t-]%c[u]", &sign, &value, unit, &stable);
04-01-2011 04:07 PM
I think you're right. It's taking the letter "g" and then filling the rest of the string with spaces that are not taken from the original buffer which is what confused me. Apparently the 'w' parameter is not enough, but adding the 't-' invokes the desired behavior. I came up with this solution myself after thinking about it for a bit:
scanneditems = Scan (buffer, "%s>%c[u]%f%c[d]%5c%c[u]", &sign, &value, unit, &stable);
unit[5] = '\0';//terminate the string
Treating it as an array of char seems to work too, but I like your solution better. Thanks!