Home >Backend Development >C++ >Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?
stringstream, string, and char* Conversion Confusion
This article addresses the issue of assigning a const char* to the string returned by stringstream.str().c_str().
Problem Explanation
stringstream.str() constructs a temporary string object that is destroyed at the end of the expression. When assigning this temporary string to a const char*, the pointer references the deleted string, resulting in garbage output.
Here's an example:
stringstream ss("this is a string\n"); const char* cstr = ss.str().c_str();
In the above code, after the expression ends, the temporary string created by stringstream.str() is deleted, causing cstr to point to an invalid memory location.
Solution
To rectify this issue, the temporary string should be copied to another string object before converting it to a const char*. This can be achieved using the following approach:
string tmp = stringstream.str(); const char* cstr = tmp.c_str();
Bonus Points Explanation
The following modified code prints the strings correctly:
cout << cstr << ss.str().c_str() << cstr2;
This modification works because:
The above is the detailed content of Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?. For more information, please follow other related articles on the PHP Chinese website!