2

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;
AlmostSurely
  • 552
  • 9
  • 22

3 Answers3

4

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

Unless you have a specific reason that you need an array of char instead of a standard string, I'd use the latter. Although it's not strictly necessary in this case, I'd also normally use a Boost lexical_cast instead of explicitly moving things through a stringstream to do the conversion:

std::string zipString = lexical_cast<std::string>(zip);

Then, if you really need the result as a c-style string, you can use zipString.c_str() to get that (though it's still different in one way -- you can't modify what that returns).

In this specific case it doesn't gain you a lot, but consistent use for conversions on this general order adds up, and if you're going to do that, you might as well use it here too.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • You gain fail fast behavior, which is a lot. I've never seen an entire organization check stream's fail bits consistently (@IniquiTrance included). – Tom Kerr Jun 29 '12 at 15:17
1

The std::string's c_str() member function returns a const char* (aka a C-style string).

std::string str = "world";
printf("hello, %s", str.c_str());
Matt
  • 21,026
  • 18
  • 63
  • 115