std::basic_ostringstream<CharT,Traits,Allocator>::str
From cppreference.com
< cpp | io | basic ostringstream
| (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 の場合にのみ、オーバーロード解決に参加します。
目次 |
[編集] パラメータ
| s | - | 基底となる文字列の新しい内容 |
| t | - | 基底となる文字列の新しい内容として使用するオブジェクト(std::basic_string_view に変換可能) |
| a | - | 返される文字列を構築するために使用されるアロケータ |
[編集] 戻り値
1,2) 基底となる文字列オブジェクトのコピー。
3) 基底となる文字列オブジェクトからムーブ構築された文字列。
4-7) (なし)
[編集] 注記
str によって返される基底となる文字列のコピーは一時オブジェクトであり、式が終わると破棄されるため、str()() の結果に対して直接 auto *ptr = out.str().c_str(); のように c_str() を呼び出すと、ダングリングポインタになります。
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_sstream_from_string_view |
202306L |
(C++26) | std::stringstream と std::string_view との連携、(7) |
[編集] 例
このコードを実行
#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"
[編集] 関連項目
| 基礎となる生文字列デバイスオブジェクトを返す (public メンバ関数) | |
| 関連する文字文字列のコピーを置き換える、または取得する ( std::basic_stringbuf<CharT,Traits,Allocator> の public メンバ関数) |