Convert double to string C++?

Mentalikryst picture Mentalikryst · Jul 14, 2009 · Viewed 159.9k times · Source

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?

Answer

Adam Rosenfield picture Adam Rosenfield · Jul 14, 2009

You can't do it directly. There are a number of ways to do it:

  1. Use a std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. Use boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. Use std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    

There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.