3

I fail to convert int to a c-string (const char*):

int filenameIndex = 1;      
stringstream temp_str;
temp_str<<(fileNameIndex);
const char* cstr2 = temp_str.str().c_str();    

There is no error but cstr2 does not get the expected value. It is initialized with some address.

What's wrong and how can I fix it?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user3165438
  • 2,631
  • 7
  • 34
  • 54
  • I guess it depends on what you mean by "convert `int` to `char*`". What is "the expected value" of a `const char*`? I'd expect it to look very much like "some address". `*cstr2` is likely to look a lot more like `1`, while `temp_str` is in scope. – johnsyweb Sep 15 '14 at 13:08
  • @Johnsyweb, I do not mind deleting the `const` if you have a better solution how to convert it. – user3165438 Sep 15 '14 at 13:09

2 Answers2

5

temp_str.str() returns a temporary object which is destroyed at the end of a statement. As such, the address pointed by cstr2 gets invalidated.

Instead, use:

int filenameIndex = 1;      
stringstream temp_str;
temp_str<<(filenameIndex);
std::string str = temp_str.str();
const char* cstr2 = str.c_str();

DEMO

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
5

temp_str.str() is a temporary string value, destroyed at the end of the statement. cstr2 is then a dangling pointer, invalidated when the array it pointed to was deleted by the string's destruction.

You'll need a non-temporary string if you want to keep hold of a pointer to it:

string str = temp_str().str();   // lives as long as the current block
const char* cstr2 = str.c_str(); // valid as long as "str" lives

Modern C++ also has slightly more convenient string conversion functions:

string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str();       // if you really want a C-style pointer

Again, this returns a string by value, so don't try cstr2 = to_string(...).c_str()

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • BTW: I would use `auto` for the variables, as long as it needs C++11 anyway due to [std::to_string](http://en.cppreference.com/w/cpp/string/basic_string/to_string). – Deduplicator Sep 15 '14 at 13:17
  • @MikeSeymour, Thanks, I would like to use the `to_string` but I get tge following compilation error: "more than one instance of overloaded function: to_string". What is missing? – user3165438 Sep 15 '14 at 13:19
  • @user3165438: Assuming you're including `` (which I guess you must be to use `string` at all), and assuming `fileNameIndex` has type `int` as indicated, it should work. Perhaps you've written a function called `to_string`, in which case qualify this with `std::`. Possibly you have a broken library: I seem to recall that some older versions of the GNU library didn't provide all the overloads of `to_string`, in which case you'd need to explicitly cast unsupported types to ones that are provided (or update your compiler). – Mike Seymour Sep 15 '14 at 13:23