简体   繁体   中英

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.

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.

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 *);`
 int i = 42;
 char buf[30];
 memset (buf, 0, sizeof(buf));
 snprintf(buf, sizeof(buf)-1, "%d", i);
 // now buf contains the "42" string.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM