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

来自cppreference.com
< cpp‎ | io‎ | basic stringbuf
std::basic_string<CharT, Traits, Allocator> str() const;
(1)
void str( const std::basic_string<CharT, Traits, Allocator>& s);
(2)

获取和设置底层字符串。

1) 创建并返回保有此 std::basic_stringbuf 底层字符序列副本的 std::basic_string 。对于仅输入流,返回的字符串含来自范围 [eback(), egptr()) 的字符。对于输入/输出或仅输出流,含有 pbase() 到序列中末字符的字符,不考虑 egptr()epptr()

为写入打开的缓冲区中的成员字符序列能为效率目的过分配。该情况下,仅返回初始化的字符:从构造函数 string 参数获得的字符、最近对 str() 的第二重载的 string 参数的字符或来自写入操作的字符。典型的使用过分配的实现维护一个高水位指针,以跟踪缓冲区已初始化部分的结尾,而此重载返回从 pbase() 到高水位指针的字符。

(C++11 起)
2) 删除此 std::basic_stringbuf 的整个底层字符序列,然后配置新的含有 s 内容副本的底层字符序列。以下列方式初始化 std::basic_streambuf 的指针:
  • 对于输入流( mode & ios_base::in == true ), eback() 指向首字符, gptr() == eback() ,而 egptr() == eback() + s.size() :后继输入将读取首个复制自 s 的字符。
  • 对于输出流( mode & ios_base::out == true ), pbase() 指向首字符而 epptr() >= pbase() + s.size() (允许 epptr 指向更远以令后随的 sputc() 不会立即调用 overflow()
    • 对于后附流( mode & ios_base::ate == true ), pptr() == pbase() + s.size() ,从而后继输出将被后附到复制自 s 的最后字符。(C++11 起)
    • 对于非后附输出流, pptr() == pbase() ,从而后继输出将重写复制自 s 的字符。

参数

s - 保有替换字符序列的 string 对象

返回值

1) 保有此缓冲的底层字符序列副本的 string 对象。
2) (无)

注意

此函数典型地通过 std::basic_stringstream::str() 访问。

示例

#include <sstream>
#include <iostream>
int main()
{
    int n;
 
    std::istringstream in;  // 亦能用 in("1 2")
    in.rdbuf()->str("1 2"); // 设置获取区
    in >> n;
    std::cout << "after reading the first int from \"1 2\", the int is " 
              << n << ", str() = \"" << in.rdbuf()->str() << "\"\n"; // 或 in.str()
 
    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); // C++11
    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_stringstream<CharT,Traits,Allocator> 的公开成员函数)