Search code examples
c++stringcstring

Converting string to C style string


I am trying to convert an int to a cstring. I've decided to read the int into a regular string via stringstream, and then read the string into a char array. The following seems to be working, but I'm wondering if I'm just getting lucky with my compiler. Does the code seem sound? Thanks!

int zip = 1234;    

char zipString[30];

stringstream str;

str << zip;

str >> zipString;

cout << zipString;

Solution

  • You can get a C++ std::string from the stream's str() function, and an immutable C-style zero-terminated string from the string's c_str() function:

    std::string cpp_string = str.str();
    char const * c_string = cpp_string.c_str();
    

    You might be tempted to combine these into a single expression, str.str().c_str(), but that would be wrong; the C++ string will be destroyed before you can do anything with the pointer.

    What you are doing will work, as long as you're sure that the buffer is large enough; but using the C++ string removes the danger of overflowing the buffer. In general, it's best to avoid C-style strings unless you need to use an API that requires them (or, in extreme circumstances, as an optimisation to avoid memory allocation). std::string is usually safer and easier to work with.