Combining Variable and Text Serial Print

At the moment I use the following:

   Serial.print(distance);
   Serial.println(" cm");

To print a variable and text on the same line. Can the 2 instructions be combined in C++?

aisc: At the moment I use the following:

   Serial.print(distance);
   Serial.println(" cm");

To print a variable and text on the same line. Can the 2 instructions be combined in C++?

You can do it with a single print line, but you'll need a few other lines to put the string together. There isn't a more efficient way to do it resource-wise. Anything you do to make it less typing will make it more program.

You could:

char buf[10];
sprintf(buf, "%d cm", distance);
Serial.println(buf);

But that's three lines of typing instead of two and you now have to link in sprintf which takes a lot of memory.

1 Like

Yes, I have done tests with sprint() and avoid it like the plague.

In PHP one can link variable and text printing with a dot like so : echo distance . " cm";

I thought C++ may have an equivalent, but appears not.