gotnull
gotnull

Reputation: 27214

Convert int to string/char C++/Arduino

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.

Upvotes: 3

Views: 22078

Answers (6)

Mike Seymour
Mike Seymour

Reputation: 254481

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 *);`

Upvotes: 3

Matteo Italia
Matteo Italia

Reputation: 126827

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.

Upvotes: 6

user406009
user406009

Reputation:

The C++ method of doing this is boost::format

std::string str = "GSM blah blah ";
str+= boost::str(boost::format("%d") % 4800);
str+= "blah blah";

Upvotes: 0

JoeFish
JoeFish

Reputation: 3100

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;
}

Upvotes: 1

Emir Akaydın
Emir Akaydın

Reputation: 5823

Try this one:

#include <iostream>

int GSM_BAUD_RATE; 
GSM_BAUD_RATE = 4800; 
char text[256];

sprintf(text, "GSM Shield running at %d baud rate.", GSM_BAUD_RATE);

Serial.println(text);

Upvotes: 0

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

Upvotes: 1

Related Questions