std::basic_stringstream<CharT,Traits,Allocator>::str
來自 cppreference.com
< cpp | io | basic stringstream
(1) | ||
std::basic_string<CharT, Traits, Allocator> str() const; |
(C++20 前) | |
std::basic_string<CharT, Traits, Allocator> str() const&; |
(C++20 起) | |
template< class SAlloc > std::basic_string<CharT, Traits, SAlloc> str( const SAlloc& a ) const; |
(2) | (C++20 起) |
std::basic_string<CharT, Traits, Allocator> str() &&; |
(3) | (C++20 起) |
void str( const std::basic_string<CharT, Traits, Allocator>& s ); |
(4) | |
template< class SAlloc > void str( const std::basic_string<CharT, Traits, SAlloc>& s ); |
(5) | (C++20 起) |
void str( std::basic_string<CharT, Traits, Allocator>&& s ); |
(6) | (C++20 起) |
template< class StringViewLike > void str( const StringViewLike& t ); |
(7) | (C++26 起) |
管理底層字串物件的內容。
1) 返回底層字串的副本。等價於 return rdbuf()->str();。
2) 返回底層字串的副本,使用 a 作為分配器。等價於 return rdbuf()->str(a);。
3) 返回一個從底層字串移動構造的字串。等價於 return std::move(*rdbuf()).str();。
4,5) 替換底層字串的內容。等價於 rdbuf()->str(s);。
6) 替換底層字串的內容。等價於 rdbuf()->str(std::move(s));。
7) 替換底層字串的內容。等價於 rdbuf()->str(t);。
此過載僅當 is_convertible_v<const T&, basic_string_view<charT, traits>> 為 true 時才參與過載決議。
目錄 |
[edit] 引數
s | - | 底層字串的新內容 |
t | - | 用作底層字串新內容的(可轉換為 std::basic_string_view 的)物件 |
a | - | 用於構造返回字串的分配器 |
[edit] 返回值
1,2) 底層字串物件的副本。
3) 從底層字串物件移動構造的字串。
4-7) (無)
[edit] 注意
str
返回的底層字串的副本是一個臨時物件,它將在表示式結束時被銷燬,因此直接在 str() 的結果上呼叫 c_str()(例如在 auto *ptr = out.str().c_str(); 中)會導致懸空指標。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_sstream_from_string_view |
202306L |
(C++26) | 將 std::stringstream 與 std::string_view 連線,(7) |
[edit] 示例
執行此程式碼
#include <iostream> #include <sstream> 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"; }
輸出
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"
[edit] 參閱
返回底層原始字串裝置物件 (public member function) | |
替換或獲取關聯字元字串的副本 (public member function of std::basic_stringbuf<CharT,Traits,Allocator> ) |