std::basic_stringstream<CharT,Traits,Allocator>::str
From cppreference.com
< cpp | io | basic stringstream
std::basic_string<CharT,Traits,Allocator> str() const; |
(1) | |
void str(const std::basic_string<CharT,Traits,Allocator>& new_str); |
(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
Run this code
#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:
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<CharT,Traits,Allocator> ) |