| (1) | |||
| (2) |
Manages the contents of the underlying string object.
1) Returns a copy of the underlying string as if by calling rdbuf()->str()
.
2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)
.
Parameters
new_str | - | new contents of the underlying string |
Return value
1) a copy of the underlying string object.
2) (none).
Notes
The copy of the underlying string returned by str
is a temporary object that will be destructed at the end of the expression, so directly calling c_str()
on the result of str()
(for example in auto *ptr = out.str().c_str();
) results in a dangling pointer.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.str( "1 2" ); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n" ; std::ostringstream out( "1 2" ); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n" ; std::ostringstream ate( "1 2" , std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n" ; } |
Output:
1 2 3 | after reading the first int from "1 2" , the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2" , str() = "3 2" after writing the int '3' to append stream "1 2" , str() = "1 23" |
See also
replaces or obtains a copy of the associated character string (public member function of std::basic_stringbuf ) |
Please login to continue.