std::basic_istringstream<CharT,Traits,Allocator>::str

(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 起)

管理底层字符串对象的内容。

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));

参数

s - 底层字符串的新内容
a - 用于构造返回的字符串的分配器

返回值

1-2) 底层字符串对象的副本。
3) 从底层字符串对象移动构造的字符串。
4-6) (无)

注解

str 所返回的底层字符串副本是将于表达式结尾析构的临时对象,故在 str() 的结果上直接调用 c_str() (例如 auto *ptr = out.str().c_str(); 中)导致悬垂指针。

示例

#include <sstream>
#include <iostream>
int main()
{
    int n;
 
    std::istringstream in;  // 亦可使用 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"

参阅

替换或获得关联字符串的副本
(std::basic_stringbuf<CharT,Traits,Allocator> 的公开成员函数)