std::istream: input stream. Input stream objects can read and interpret input from sequences of characters. The standard object cin is an object of this type.
标准中定义的std::cin就是istream类型。istream是std::basic_istream类模板的一个实例化。
c++中定义的标准输入输出流是istream和ostream,他们是iostream类的父类,而cin是istream的对象,cout是ostream的对象。头文件fstream(对文件操作的流)包含了ifstream和ofstream,头文件sstream(对字符串操作的流)包含了istringstream和ostringstream,这些类都是继承自istream和ostream的。它们的关系如下图:

缺省情况下,输入操作符丢弃空白符、空格符、制表符、换行符以及回车。如果希望读入上述字符,或读入原始的输入数据,一种方法是使用istream的get()成员函数来读取一个字符,另一种方法是使用istream的getline()成员函数来读取多个字符。istream的read(char* addr, streamsize size)函数从输入流中提取size个连续的字节,并将其放在地址从addr开始的内存中。istream成员函数gcount()返回由最后的get()、getline()、read()调用实际提取的字符数。read()一般多用在读取二进制文件,读取块数据。
输入流有三个函数来测试流状态:即bad(),fail()和eof()。ignore()用来抛掉指定个数的缓冲区中的字节。如果bad()为真,代表是遇到了系统级的故障。如果fail()为真,则表示输入了非法的字符。
其它的istream成员函数:putback( char c ) 将字符放回iostream;unget()往回重置”下一个”istream项;peek()返回下一个字符或EOF,但不要提取出来。
以下是测试代码:
#include <iostream>
#include <fstream>
#include <string>
#include "istream.hpp"
void test_istream()
{
//std::istringstream
std::filebuf in;
if (!in.open("E:/GitCode/Messy_Test/testdata/istream.data", std::ios::in)) {
std::cout << "fail to open file" << std::endl;
return;
}
std::istream iss(&in);
std::string str;
int count = 0;
while (!iss.eof()) {
if (iss.bad()) {
std::cout << "input stream corrupted" << std::endl;
break;
}
if (iss.fail()) {
std::cout << "bad data" << std::endl;
iss.clear(std::istream::failbit);
iss.ignore(256, '\n');
continue;
}
std::getline(iss, str);
if (str == "#filename:") {
iss >> str;
std::cout << "file name: " << str << std::endl;
}
if (str == "#content:") {
std::getline(iss, str);
std::cout << "file content: " << str << std::endl;
}
if (str == "#add operation:") {
int a, b;
iss >> a >> b;
std::cout << "a + b = " << (a + b) << std::endl;
}
if (str == "#char array:") {
char a, b, c, d, e, f;
iss >> a >> b >> c >> d >> e >> f;
std::cout << a << " " << b << " " << c << " " << d << " " << e << " " << f << std::endl;
}
if (str == "#int array:") {
int arr[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
iss >> arr[i][j];
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
if (str == "#mean value:") {
float mean_value;
iss >> mean_value;
std::cout << "mean_value = " << mean_value << std::endl;
}
}
in.close();
}