How to append an Integer to a String?

Hi. i am trying to convert a string to an integer, but i keep getting this error.

This is my code:

int led=D7;
String oatmeal;
String sugar;
String hours;
String minutes;
int sep[5];
int o;
void setup() {
  pinMode(led, OUTPUT); // set the D7 LED as output
  Spark.function("dispenser",blinkfunc);    // a POST request for "blink" will reference blinkfunc, defined below
// call the below function when the POST request matches it
int blinkfunc(String command) {
  int index = 0;
  Serial.println("raw: " + command);
  for(int i = 0; i < command.length(); i++){
    if(command.charAt(i) == ',') {        
      sep[index] = i;
    oatmeal = command.substring(sep[0]+1, sep[1]);
    sugar = command.substring(sep[1]+1, sep[2]);
    hours = command.substring(sep[2]+1, sep[3]);
    minutes = command.substring(sep[3]+1, sep[4]);
    o = oatmeal.toInt();
  Serial.println("Oatmeal: " + oatmeal);
  Serial.println("sugar: " + sugar);
  Serial.println("hours: " + hours);
  Serial.println("minutes: " + minutes);
  Serial.println("converted: " + o);
  return 1;   // return 1 to show that this worked.
void loop() {
  //not doing anything here 

the POST i send to the function looks like this:


and the console would throw me this:

raw: ,1,1,8,30,
Oatmeal: 1
sugar: 1
hours: 8
minutes: 30

Now. what i wanted, is the


to look like this:

converted: 1

but the c keeps dissappearing, and the actual “o” value is nonexistent.

So how would i go about converting the “oatmeal” string to int?

Thanks alot in advance :smile:

1 Like

Try this instead

  Serial.print("converted: ");
  // or
  Serial.println("converted: " + String(o));
  // or
  char s[32];
  sprintf(s, "converted: %d", o);
  // or just use the "oatmeal" string you already have
  // or multiple other ways

The thing is that your first print statements do contain a String object and a “string literal” which will trigger the String concatenation operator to kick in and call the println overload that takes a String object.
But your last print only contains a string literal (wich is of type const char*) and an int which does not perform a string concatenation but is seen as a pointer offset (hence the missing c - try sending 4 for oatmeal and you’ll loose conv).

So it’s actually not an issue to convert String to int but how to concatenate string literals and integers (or any other numeric type), thus I’m going to alter your topic title (original “How to convert String to Integer?”) :wink:


Ah i see! Thank you very much! :slight_smile: