Splitting a string and assigning to fields

Hi,

If I had a string like:

char payload[32] = "100 2 5 7";

How could I split it on the spaces and assign the numbers to variables like

Id = 100

temp = 2

humidity = 5 

direction = 7

Thanks

strtok for splitting character arrays

Or sprintf sscanf :wink:

Edit: often mixing sprintf and sscanf for some reason :confused:

Thought you were passing in a struct as your payload? Just cast the pointer of the first element to your struct type and it will fill in your variables for you.

Indeed strtok for splitting the arrays but that gives you new strings. To make them to int values use:

void setup(){
  char multiDecString[] = "100 2 5 7";
  
  int id = strToInt(strtok(multiDecString, " "));
  int temp = strToInt(strtok(NULL, " "));
  int humidity = strToInt(strtok(NULL, " "));
  int direction = strToInt(strtok(NULL, " "));
}

void loop(){
  
}

unsigned int strToInt(char *str){
  byte i = 0;
  unsigned int rtn = 0;
  while(str[i]){
    if(str[i] >= 0x30 && str[i] < (0x30 + 10)){
      rtn *= 10;
      rtn += (str[i] - 0x30);
      i++;
    }
    else{
      break;
    }
  }
  return rtn;
}

@septilion: is there something wrong with atoi ?

Nope, nothing wrong with that. But in my searches I only found stoi which isn't part of Arduino. atoi works the same as my code :stuck_out_tongue: It's indeed easier to use that. :smiley: Unless you would like to be able to pass binary or hex as well. Then my code is easy adaptable.

There is a parse example in serial input basics that shows how to convert strings to numbers

...R