Sscanf comma separated string and value

Hi, I have a question about this code, can I use sscanf to seperate mystring1 ? When I had "1,new" it worked but when string is first "new,1" it doesn't work because as led_on_off it returns "new,1"

mystring1 = "new,1";
 
  char new[50];
  mystring1.toCharArray(new,50);

 

int led_bright;
char led_on_off[10];

  if(sscanf(new, "%s,%d",led_on_off,&led_bright)==2)
{
Serial.println(led_bright);
Serial.println(led_on_off);

strtok() would be a better choice.

Hello

%s will read until a whitespace. As there is no whitespace in your string, it will read the entire string new,1 and your if condition will fail because sscanf didn't return 2

Instead of %s you have to use something like %[^,] which means read everything until ,

And side note, I would not use new for the buffer name…

The new operator is a reserved keyword (technically an operator which denotes a request for memory allocation on the Heap).

void setup() {
  Serial.begin(115200);
  String mystring1 = "new,1";
  char new1[50];
  mystring1.toCharArray(new1,50);
   
  int led_bright;
  char led_on_off[10];

  if (sscanf(new1, "%[^,],%d", led_on_off, &led_bright) == 2)
  //if(sscanf(new1, "%s,%d",led_on_off,&led_bright)==2)
  {
    Serial.println(led_bright);
    Serial.println(led_on_off);
  }
}

Or, leaving out the useless String:

void setup() {
  Serial.begin(115200);
  char line[] = "new,1";
  int led_bright;
  char led_on_off[10];
  int x = sscanf(line, "%[^,],%d", led_on_off, &led_bright);
  if (x == 2)
    //if(sscanf(new1, "%s,%d",led_on_off,&led_bright)==2)
  {
    Serial.println(led_bright);
    Serial.println(led_on_off);
  }
}
void loop() {}

how does it let you compile? new is a reserved keyword nkw9pu - Online C++0x Compiler & Debugging Tool - Ideone.com

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.