Hi, I have a comma delimited string that I need to separate it in substring and save it in variables of a structure, to separate it I am using strtok, and I can print it through the serial port, but how do I save it in the variables?
char Mystring[50] = "Hello,World!";
char * token;
char * strings[3]; // pointers to strings to receive the parsed data
struct words
{
char one[8]; // sorry, I don't use Strings
char two[8];
};
void setup()
{
struct words Mywords;
Serial.begin(115200);
Serial.println();
byte index = 0; // index to index the strings array
token = strtok(Mystring, ","); // get the first part
while (token != NULL )
{
strings[index] = token; // put the parsed part into the array
index++; // increment the array position
Serial.println( token ); //printing each token
token = strtok(NULL, ","); // get the next part
}
strcpy(Mywords.one, strings[0]);
strcpy(Mywords.two, strings[1]);
Serial.print("Mywords.one = ");
Serial.print(Mywords.one);
Serial.print(" Mywords.two = ");
Serial.println(Mywords.two);
}
void loop()
{
}
I added an array of pointers to receive the parsed parts and an index to increment the array position as the parts are parsed.
I changed the struct to strings because I do not like using String and frankly don't know much about handling them.
If you are willing to settle for an array of C-strings instead, this works:
char Mystring[50] = "Hello,World!";
char * token;
char strings[2][10] = {0}; //two strings to receive the parsed data (each 9 characters max)
void setup()
{
Serial.begin(9600);
Serial.println();
byte index = 0; // index to index the strings array
token = strtok(Mystring, ","); // get the first part
while (token != NULL )
{
strcpy(strings[index], token); //safer: use strncpy() instead
Serial.println( strings[index] ); //printing each substring
index++; // increment the array position
token = strtok(NULL, ","); // get the next part
}
}
void loop()
{
}