Go Down

Topic: Query about odd behaviour of strspn() function (Read 593 times) previous topic - next topic

donb

I'm trying to parse input data presented in the form B11=<digits>. "B11" is the parameter name.
To ensure I'm looking at a valid input parameter, I'm testing the input (a char array in RxBuffer[]) as follows:
if (strspn(RxBuffer,"B11="))==4)
But I'm getting unpredictable results. Below are some sample input data, prefaced with the corresponding return value of strspn():
0 - fred (ok)
4 - B11=abc (ok)
4 - B11=012 (ok)
5 - B11=123 (eh ?)
4 - B11=234 (ok)
6 - B11=1123 (eh ?)
7 - B11=11123 (eh ?)
It seems that if the string starts with the digit '1', something goes wrong. Any ideas ?
For reference, the test code is running on an Arduino Mega 2560 board.
Cheers, Don

PaulS

The strspn() function returns the length of the initial portion of str1 which consists only of characters that are part of str2. The return value is not the length of str2, if str2 is contained in str1.

So, it appears that the output you are seeing is reasonable.

The strspn() function is not what you want to be using. You want to use strtok(), with "=" as the delimiter string, to get the "B11" portion. Compare that to "B11" to see if they match. If so, call strtok() again, with NULL as the first argument and "\0" as the second argument. The token returned will be the digits part, which you can pass to atoi(), atol(), atof(), etc. as needed.

donb

Paul,
Thanks - that's excellent.
After posting, I started thinking a bit harder what exactly strspn() did, and in fact the definition of strcspn() gave me a bit more of a clue. Your guidance is much appreciated - it'll be easy to rework my code a bit more sensibly.
Cheers,
Don

Go Up