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

来自cppreference.com

std::basic_string<CharT,Traits,Allocator> str() const;
(1)
void str(const std::basic_string<CharT,Traits,Allocator>& new_str);
(2)

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

1) 返回底层字符串的副本,如同通过调用 rdbuf()->str()

2) 替换底层字符串,如同通过调用 rdbuf()->str(new_str)

参数

new_str - 底层字符串的新内容

返回值

1) 底层字符串对象的副本。

2) (无)

注意

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> 的公开成员函数)