简介
std::stringstream
typedef basic_stringstream<char> stringstream;
流类对字符串进行操作。
此类的对象使用包含字符序列的字符串缓冲区(string buffer)。可以使用作为string对象的成员str直接访问这个字符序列。
可以使用在输入和输出流上允许的任何操作从流中插入和/或提取字符。
带有以下模板参数的basic_stringstream的实例:
| 模板参数 | 定义 | 描述 |
|---|---|---|
| charT | char | 作为成员char_type的别名 |
| traits | char_traits<char> | 作为成员traits_type的别名 |
| Alloc | allocator<char> | 作为成员allocator_type的别名 |
除了内部string buffer之外,这些类的对象还保留一组从ios_base、ios和istream继承的内部字段:

成员类型
| 成员类型 | 定义 |
|---|---|
| char_type | char |
| traits_type | char_traits<char> |
| allocator_type | allocator<char> |
| int_type | int |
| pos_type | streampos |
| off_type | streamoff |
以下这些成员类型继承自其基类istream、ostream和ios_base:

公有成员函数
➊构造函数:
default (1) explicit stringstream(ios_base::openmode which = ios_base::in | ios_base::out);
initialization (2) explicit stringstream(const string& str, ios_base::openmode which = ios_base::in | ios_base::out);
copy (3) stringstream(const stringstream&) = delete;
move (4) stringstream(stringstream&& x);
// swapping ostringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream ss;
ss << 100 << ' ' << 200;
int foo, bar;
ss >> foo >> bar;
std::cout << "foo: " << foo << '\n';
std::cout << "bar: " << bar << '\n';
return 0;
}
foo: 100
bar: 200
代码解释:
ostream& operator<< (someType val);
参数val:Value to be formatted and inserted into the stream.
要格式化并插入到流中的值。
istream& operator>> (someType& val);
参数val:Object where the value that the extracted characters represent is stored.
对象,其中存储提取的字符所表示的值。
stringstream ss;
ss << 100;// 100这个int型值插入到流ss中。
ss >> foo;// 提取流ss中的值并存储到对象foo中。
➋str
string str() const;// get
void str (const string& s);// set
// stringstream::str
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream, std::stringbuf
int main () {
std::stringstream ss;
ss.str("Example string");
std::string s = ss.str();
std::cout << s << '\n';
return 0;
}
Example string
➌operator=
copy (1) stringstream& operator= (const stringstream&) = delete;
move (2) stringstream& operator= (stringstream&& rhs);
➍swap
void swap (stringstream& x);
Exchanges all internal data between x and *this.
// swapping stringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream foo;
std::stringstream bar;
foo << 100;
bar << 200;
foo.swap(bar);
int val;
foo >> val; std::cout << "foo: " << val << '\n';
bar >> val; std::cout << "bar: " << val << '\n';
return 0;
}
foo: 200
bar: 100
其他继承而来的函数

本文详细介绍了C++标准库中的stringstream类,包括构造函数、str成员函数、赋值运算符以及交换函数的用法。stringstream允许将字符串视为输入/输出流,方便进行文本操作。通过示例展示了如何插入和提取数据,以及如何设置和获取内部字符串。
2538

被折叠的 条评论
为什么被折叠?



