Jimmie
January 13, 2020, 5:08pm
1
What is the correct sscanf format for reading the stream below? I tried the following but it does not work:
char myMsg[40];
char myStart[2];
String theMsg = "$S,12.34,56,78,2000,&"
theMsg.toCharArray(myMsg, theMsg.length() + 1);
double dVal;
int D1, D2, Count;
sscanf(myMsg, "%s,%f,%d,%d,%d", myStart, &dVal, &D1, &D2, &Count);
Thanks in advance.
float
is not supported.
For floats you need to do it in two steps
read the value into a string variable (e.g. via %[^,]
- Iād also use that for the starting $S
)
use atof()
to convert that string into a float
Jimmie
January 13, 2020, 5:51pm
4
Thank you @Scruffr .
I am using
String theMsg = "$S,12.34,56,78,2000,&"
because the library I am using stores theMsg is a String variable.
I tried the code below but sVal does not have the right values ā¦
char myMsg[40];
char myStart[2];
char sVal[5];
String theMsg = "$S,12.34,56,78,2000,&"
theMsg.toCharArray(myMsg, theMsg.length() + 1);
double dVal;
int D1, D2, Count;
sscanf(myMsg, "%s,%s,%d,%d,%d", myStart, sVal, &D1, &D2, &Count);
That is exactly what I meant when I wrote the above
Jimmie
January 13, 2020, 5:54pm
6
Thanks @Scruffr . I am just not familiar enough with C notations.
Will try to follow your post again.
Jimmie
January 13, 2020, 5:56pm
7
ScruffR:
%[^,]
THANK YOU. Worked now. Used:
sscanf(myMsg,"%[^,],%[^,],%d,%d,%d",
Let me a bit more direct
char myStart[4]; // you need the space for the zero-terminator too
char sVal[12];
double val;
int parsed = sscanf(myMsg, "%[^,],%[^,],%d,%d,%d,&", myStart, sVal, &D1, &D2, &Count);
if (parsed == 5) // always advisable to check wheter all data could be parsed
val = atof(sVal);
1 Like