Convert double to string C++?


Possible Duplicate:
How do I convert a double into a string in C++?

I want to combine a string and a double and g++ is throwing this error:

main.cpp: In function ‘int main()’:
main.cpp:40: error: invalid operands of types ‘const char [2]’ and ‘double’ to binary ‘operator+’

Here is the line of code which it is throwing the error on:

storedCorrect[count] = "("+c1+","+c2+")";

storedCorrect[] is a string array, and c1 and c2 are both doubles. Is there a way to convert c1 and c2 to strings to allow my program to compile correctly?

5/23/2017 12:32:10 PM

Accepted Answer

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

9/25/2015 10:09:22 PM

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow