Parsing a string to int

Hey,

I have a problem working with strings, cause I lost that C language lecture, so I don't know how to split and string and put the values inside a integer variables.

I've got a string comming from my serial like this: 51,20,11

And I would like to have in the end: A = 51
B = 20
C = 11
where A,B,C are integers.

void loop() {
	while (Serial.avaiable()>0) {	
                 data = Serial.read();
                 char *p = data;
                 char *str;
                 while ((str[i] = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                        Serial.println(str);
                }
	}
}

The serial output give me:
50
22
11

With this I split my string but I don't know how to save the data to an array and then convert it to an integer.

Thank you :slight_smile:

  • itoa(s); // in case of a char array
  • String.toint() // arduino v22 iirc.

you could use atoi().

                 while ((str = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                        my_int_array[idx++] = atoi(str);
                        Serial.println(str);
                }

Note, that there is a programming mistake inside the while condition (compare you input vs. our output)

Oliver

thank you for your answer, but the problem is that I don't know how to write this. Could you write me how is going to be?

I appreciate your time.

Thank you. Now it's working. Here the code.

void loop() {
		
	if (Serial.avaialable()>0) {
                 data = Serial.read();
                 int i = 0;
                 char *p = data;
                 char *str;
                 while ((str = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                        my_int_array[i++] = atoi(str);
                }
                a = my_int_array[0];
                b = my_int_array[1];
                c = my_int_array[2];
                Serial.print("A: ");
                Serial.println (a);
                Serial.print("B: ");
                Serial.println (b);
                Serial.print("C: ");
                Serial.println (c);
	}
}

One last question, is it possible to print everything at the same time? like Serial.println ("C: " + c)

One last question, is it possible to print everything at the same time? like Serial.println ("C: " + c)

No.
Thought there is an iostream-like template around somewhere