Help with sscanf


#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.


#2

float is not supported.
For floats you need to do it in two steps

  1. read the value into a string variable (e.g. via %[^,] - I’d also use that for the starting $S)
  2. use atof() to convert that string into a float

#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);

#5

That is exactly what I meant when I wrote the above


#6

Thanks @Scruffr. I am just not familiar enough with C notations.

Will try to follow your post again.


#7

THANK YOU. Worked now. Used:

sscanf(myMsg,"%[^,],%[^,],%d,%d,%d",


#8

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);