std::basic_stringstream<CharT,Traits,Allocator>::str
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (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() 的结果上直接调用 c_str()(例如 auto *ptr = out.str().c_str(); 中)会导致悬垂指针。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_sstream_from_string_view |
202306L |
(C++26) | 字符串流的 std::string_view 接口,(7) |
示例
运行此代码
#include <iostream>
#include <sstream>
int main()
{
int n;
std::istringstream in; // 也可以使用 in("1 2")
in.str("1 2");
in >> n;
std::cout << "从 \"1 2\" 读取第一个 int 后,该 int 是 "
<< n << ",str() = \"" << in.str() << "\"\n";
std::ostringstream out("1 2");
out << 3;
std::cout << "将 int '3' 写入输出流 \"1 2\" 后"
<< ",str() = \"" << out.str() << "\"\n";
std::ostringstream ate("1 2", std::ios_base::ate);
ate << 3;
std::cout << "将 int '3' 写入后附流 \"1 2\" 后"
<< ",str() = \"" << ate.str() << "\"\n";
}
输出:
从 "1 2" 读取第一个 int 后,该 int 是 1,str() = "1 2"
将 int '3' 写入输出流 "1 2" 后,str() = "3 2"
将 int '3' 写入后附流 "1 2" 后,str() = "1 23"
参阅
| 返回底层原生字符串设备对象 (公开成员函数) | |
| 替换或获得关联字符串的副本 ( std::basic_stringbuf<CharT,Traits,Allocator> 的公开成员函数)
|