3

I am working on the particle.io Spark platform, currently stuck trying to print out a float as a string. I saw some solutions where you use a string stream to convert the float.

My implementation is as follows below:

#include <sstream>

void loop()
{
    float tempC = 21.35;

    std::ostringstream stream;
    stream << tempC;
    std::string tempCString = stream.str();

    // why does this give me a blank string?
    Serial.print("Temp 1: ");
    Serial.println(tempCString.c_str());

    // while this outputs the float
    Serial.print("Temp 2: ");
    Serial.println(tempC);

    Serial.println(tempCString.size());
}

This results in the following output:

Temp 1:
Temp 2: 21.35
6

Also, this fails to compile:

Serial.println(tempCString);

With the following error:

error: no matching function for call to 'USBSerial::println(std::string&)'

Edit: link to particle docs about Serial.print

https://docs.particle.io/reference/firmware/core/#print-

koverda
  • 99
  • 1
  • 8

1 Answers1

0

I found the answer. Not sure if this holds true for regular c++, but for the version of c++ running on the particle spark, the solution is as follows:

float myFloat = 6.123;
String floatString(myFloat, 2);

This gives me a string that I can work with!

koverda
  • 99
  • 1
  • 8