Convert int to string/char C++/Arduino

16,899

Solution 1

If, as it seems, you are working on an Arduino project, you should simply let the Serial object deal with it:

int GSM_BAUD_RATE;
GSM_BAUD_RATE = 4800;

Serial.print("GSM Shield running at ");
Serial.print(GSM_BAUD_RATE);
Serial.println(" baud rate.");

since the print and println methods have overloads to handle several different types.

The other methods can be useful on "normal" machines, but stuff like string and ostringstream require heap allocation, which, on an Arduino board, should be avoided if possible due to the strict memory constraints.

Solution 2

UPDATE: this answers the original question, before it was updated to mention Arduino. I'm leaving it, as it is the correct answer for non-embedded systems.

You can create a formatted string using a stringstream, and extract a string from that.

#include <sstream>

std::ostringstream s;
s << "GSM Shield running at " << GSM_BAUD_RATE << " baud rate.";

Serial.println(s.str().c_str()); // assuming `println(char const *);`

Solution 3

You could use a stringstream:

int main()  
{
    int myInt = 12345;
    std::ostringstream ostr;
    ostr << myInt;
    std::string myStr = "The int was: " + ostr.str();
    std::cout << myStr << std::endl;
}

Solution 4

 int i = 42;
 char buf[30];
 memset (buf, 0, sizeof(buf));
 snprintf(buf, sizeof(buf)-1, "%d", i);
 // now buf contains the "42" string.
Share:
16,899
fulvio
Author by

fulvio

Updated on June 04, 2022

Comments

  • fulvio
    fulvio almost 2 years

    This has got to be the easiest thing to do in C++.

    ..and I know it's been asked many many times before, however please keep in mind that this is part of an Arduino project and memory saving is a major issue as I've only got 32256 byte maximum to play with.

    I need to convert an integer to a string.

    int GSM_BAUD_RATE;
    GSM_BAUD_RATE = 4800;
    
    Serial.println("GSM Shield running at " + GSM_BAUD_RATE + " baud rate.");
    

    Obviously the last line is going to give me an error.

    Thanks in advance.