3

I'm working on an arduino assignment that splits an incoming string and puts the terms of the string in 6 different variables( a sample input string when split up has 6 terms). i have the following error popping up: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)' . Can you guys suggest changes to the code to get it right ?

String str(" ");
char a[5],b[5],c[5],d[5],e[5],f[5];
char *token = strtok(str, " ");


void setup()
{
Serial.begin(9600);

 }
void loop(){
while (!Serial.available());
str = Serial.readStringUntil('\n');
Serial.println(str);

strcpy(a,token);

token = strtok(NULL, " ");
strcpy(b,token);
token = strtok(NULL, " ");
strcpy(c,token);
token = strtok(NULL, " ");
strcpy(d,token);
token = strtok(NULL, " ");
strcpy(e,token);
token = strtok(NULL, " ");
strcpy(f,token);

Serial.println(a);
Serial.println(b);
Serial.println(c);
Serial.println(d);
Serial.println(e);
Serial.println(f);
}

enter code here

2 Answers2

3

You need to convert str to char array, because strtok expects char* argument, not String.

String str("...");
char str_array[str.length()];
str.toCharArray(str_array, str.length());
char* token = strtok(str_array, " ");
VLL
  • 9,634
  • 1
  • 29
  • 54
3
// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator)
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len];

// Copy it over 
str.toCharArray(char_array, str_len);
Mohammad Lotfi
  • 369
  • 5
  • 16