IO库类型和头文件
iosteam头文件中定义了:
istream(从流中读取);//cin
ostream(写到流中);//cout;cerr;clog
iostream(对流进行读写,从istream和osteam派生而来)
fsteam头文件中定义了:
ifstream(从文件中读取,由istream派生而来);
ofstream(写到文件中去,由ostream派生而来);
fstream(对文件进行读写,由iostream派生而来);
ssteam头文件中定义了:
istringstream(从string对象中读取,由istream派生而来);
ostringstream(写到string对象中去,由ostream派生而来);
stringstream(对string对象进行读写,由iostream派生而来);
IO对象无拷贝和赋值
ofstream out1, out2;
out1 = out2;//不能对流赋初值
ofstream print(ofstream);//不能初始化ofstream参数
out2=print(out2);//不能拷贝流对象
IO流的条件状态
//strm值得是流类 如iostream fstream等
strm::iostate // 机器相关的整型名,由各个iostream类定义,用于定义条件状态
strm::badbit // strm::iostate类型的值,用于指出被破坏的流
strm::failbit // strm::iostate类型的值,用于指出失败的IO操作
strm::eofbit // strm::iostate类型的值,用于指出流已经到达文件结束符
s.eof() // 如果流s的eofbit置位,则该函数返回true
s.fail() // 如果流s的failbit置位,则该函数返回true
s.bad() // 如果流s的badbit置位,则该函数返回true
s.good() // 如果流s处于有效状态,则该函数返回true
s.clear() // 将流s中的所有状态值都重设为有效状态
s.clear(flag) // 将流s中的某个指定条件状态设置为有效。flag的类型是strm::iostate
s.setstate(flag) // 给流s添加指定条件。flag的类型是strm::iostate
s.rdstate() // 返回流s的当前条件,返回值类型为strm::iostate
- 下面是一个简单的例子
using namespace std;
cout << iostream::goodbit << iostream::badbit << iostream::eofbit << iostream::failbit << endl; // 输出 0 1 2 4
iostream::iostate coutstate = cin.rdstate(); // 得到cin对象的原始状态值
cout << coutstate << endl; // 输出 0 cin的状态值是 std::iostream::goodbit
int i;
cin >> i; // 输入"123"
cout << cin.rdstate() << endl; // 输出 0 因为“123”可以被正确转成int并被存入i 所以cin的状态置为 std::iostream::goodbit
cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 1 0 0 0
cin >> i; // 输入"abd"
cout << cin.rdstate() << endl; // 输出 4 因为“abc”无法转成int存入i 所以cin的状态置为 std::iostream::failbit
cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 0 0 1 0
cin.clear(); // 重置cin状态为std::iostream::good 否则下面的cin << i 不会执行, 或者这样设置cin.clear(std::iostream::failbit)
cin >> i; // 输入"568"
cout << cin.rdstate() << endl; // 输出 0 因为“568”可以被正确转成int并被存入i 所以cin的状态置为 std::iostream::good
cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 1 0 0 0
缓冲区的刷新
以下几种情况会引起缓冲区刷新
- 缓冲区满时;
- 执行flush语句;
- 执行endl语句;
- 关闭文件。
对于缓冲区刷新的理解可以有助于我们进行代码调试,未输出信息的语句在程序中不一定没有执行,有可能还在缓冲区,需要用flush或endl刷新输出,有助于我们尽快定位错误位置。