定义于头文件 <istream>
template< class CharT, |
类模板 basic_istream
提供字符流上的高层输入支持。受支持操作包含带格式的输入(例如整数值或空白符分隔的字符与字符串)和无格式输入(例如未处理字符和字符数组)。此功能以通过 basic_ios
基类访问的底层 basic_streambuf
类所提供的接口实现。大多数库实现中, basic_istream
有一个非继承数据成员:用于存储 basic_istream::gcount() 所返回的值。
杂项
与底层存储设备同步
std::basic_istream<CharT,Traits>::sync
int sync(); |
将输入缓冲区与关联数据源同步。
表现为无格式输入函数 (UnformattedInputFunction) ,除了不影响 gcount() 构造并检查 sentry 对象后,
若 rdbuf() 为空指针,则返回 -1 。
否则调用 rdbuf()->pubsync() 。若该函数返回 -1 ,则调用 setstate(badbit) 并返回 -1 。否则返回 0 。
参数
(无)
返回值
成功时为 0 ,失败时或若流不支持此操作(无缓冲)则为 -1 。
注意
同 readsome() ,此函数是否对库提供的流做任何事是实现定义的。意图典型地是为了令下个读取操作拾取任何在流缓冲最后填充其获取区后,可能已对关联输入序列做出的更改。为达成之, sync()
可以清空获取区,或重填充它,或不做任何事。值得注意的例外是 Visual Studio ,其中此操作在以标准输入流调用时舍弃未处理的输出。
调用示例
#include <iostream>
#include <fstream>
void file_abc()
{
std::ofstream f("test.txt");
f << "abc\n";
}
void file_123()
{
std::ofstream f("test.txt");
f << "123\n";
}
int main()
{
file_abc(); // 文件现在含 "abc"
std::ifstream f("test.txt");
std::cout << "Reading from the file\n";
char c;
f >> c;
std::cout << c;
file_123(); // 文件现在含 "123"
f >> c;
std::cout << c;
f >> c;
std::cout << c << '\n';
f.close();
file_abc(); // 文件现在含 "abc"
f.open("test.txt");
std::cout << "Reading from the file, with sync()\n";
f >> c;
std::cout << c;
file_123(); // 文件现在含 "123"
f.sync();
f >> c;
std::cout << c;
f >> c;
std::cout << c << '\n';
}
输出
交换流对象,除了关联的缓冲区
std::basic_istream<CharT,Traits>::swap
protected: | (C++11 起) |
调用 basic_ios::swap(rhs) 交换基类的所有数据成员,除了 rdbuf() ,再交换 *this 和 rhs
间的 gcount() 计数器值。此 swap 函数受保护:它为可交换输入流类 std::basic_ifstream 和 std::basic_istringstream 的 swap 函数所调用,它们知道如何正确地交换关联流缓冲。
参数
rhs | - | 与之交换的同一类型的不同 basic_istream 对象 |
调用示例
#include <sstream>
#include <iostream>
#include <utility>
int main()
{
std::istringstream s1("hello");
std::istringstream s2("bye");
s1.swap(s2); // OK : istringstream 拥有公开的 swap()
std::swap(s1, s2); // OK :调用 s1.swap(s2)
// std::cin.swap(s2); // 错误: swap 是受保护成员
std::cout << s1.rdbuf();
}
输出