How to print Integer alongside String Arduino?

10,275

Solution 1

There is a huge difference between Arduino String class and regular C-string. The first one overloads addition operator, but there is almost excessive usage of dynamic memory. Mainly if you use something like:

String sth = String("blabla") + intVar + "something else" + floatVar;

Much better is just using:

Serial.print("Series : ");
Serial.println(cmdSeries);

Btw, this string literal resides in Flash and RAM memory, so if you want to force using flash only:

Serial.print(F("Series : "));

But it's for AVR based Arduinos only. This macro can save a lots of RAM, if you are using lots of literals.

EDIT: Sometimes I use this:

template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

Serial << F("Text ") << intVar << F("...") << "\n";

It prints each part separately, no concatenations or so.

Solution 2

Try this

int cmdSeries = 3;
Serial.println(String("Series : ") + cmdSeries);
Share:
10,275
The Little Cousin
Author by

The Little Cousin

Hobbyist, I like to work on my personal Home-Automation project at home Using Arduino~Uno and C# Visual Studio and to program for fun. Front-End Web-Development &amp; Graphic Design.

Updated on June 04, 2022

Comments

  • The Little Cousin
    The Little Cousin almost 2 years

    I am trying to print an integer alongside a string but it's not really working out and am getting confused.

    int cmdSeries = 3;
    
    Serial.println("Series : " + cmdSeries);// That's where the problem occur
    

    In visual basic we used to do it this way:

    Dim cmdSeries As Integer
    Console.Writeline(""Series : {0}", cmdSeries)
    

    So i've tried it with Serial.println but it returns this error : call of overloaded 'println(const char [14], int&)' is ambiguous

    Can anyone help my out, I want to achieve this without using any libraries and in a clean way.

  • The Little Cousin
    The Little Cousin about 7 years
    Interesting, isn't there any other clean methods, if I have to print 20 values with text it's going to be super difficult hasn't anybody found any solution or haven't even the Arduino Devs though about it?
  • KIIV
    KIIV about 7 years
    Sometimes I'm using overloaded operator<< to do that. I just have to find the right sketch :)
  • KIIV
    KIIV about 7 years
    @The_Little_Cousin Updated. It's using Print interface, so it can be used with many other classes. However no formatting support.