C++ IO类(1) 流的介绍和流的状态

基本IO库类型:
istream(输入流)类型, 提供输入操作
ostream(输出流)类型,提供输出操作
cin, 一个istream对象,从标准输入读取数据
cout, 一个ostream对象,向标准输出写数据
cerr,一个ostream对象,通常用于输出程序错误信息,写入到标准错误
>>: 用来从一个istream对象读取输入数据
<<: 用来向一个ostream对象写入数据
getline:从一个给定的istream读取数据,并存入string对象

文件IO类:
应用程序常常需要读写命名文件,所以我们可以通过fstream向文件读写数据
ifstream 从文件读取数据 ofstream 向文件写入数据
fstream 读写文件

字符串IO类:
istringstream 从字符串读取数据
ostringstream 向字符串写入数据

ifstream和istringstream都继承于istream 所以使用方法类似

IO对象无对象或拷贝:
#include
#include
#include
using namespace std;

int main() {

	ofstream out1, out2;
	out1 = out2; //流对象不能赋值
	ofstream print(ofstream);  //不能初始化ofstream参数
	out2 = print(out2);    //不能拷贝流对象


	system("PAUSE");
	return 0;
}

进行IO操作的函数一般使用引用方式,读写一个IO对象会改变其状态
传递和返回的引用不能是const的

检测流输入是否正确:
读操作有时候会发生错误: 如int ival; cin>> ival;
如果输入Boo则会发生错误 无法正确读取数据,因此,要进行检测
#include
#include
#include
using namespace std;

void TestIstreamRight() {
	int ival;
	if (cin >> ival)
		cout << "right" << endl;
	else
		cout << "wrong" << endl;
}
int main() {

	TestIstreamRight();
	
	system("PAUSE");
	return 0;
}

查询流的状态:
有时候我们也需要知道IO输入输出为什么会发生错误,这时候需要流状态检测,然后选择正确的处理方式
IO库定义了一个与机器无关的IOSTATE类型,它提供了表达流状态的完整功能
badbit表示系统级错误:如不可恢复或读写错误,一旦被置位,便不可再被恢复
failbit:发生可恢复错误后,failbit被置位,该错误可被修正
一个文件读取结束后:
eofbit和failbit都会被置位,goodbit的值为,表示未发生错误
badbit,failbit,eofbit任意一个被置位后,表示发生错误

管理条件状态:
rdstate();   //记住cin当前的状态
setstate函数将给定条件位置位,表示发生对应错误

clear复位对应操作位; 

检测各个位是否被改变:
void CheckBit() {
	if (cin.eof()) {
		cout << "eof change!" << endl;
	}

	if (cin.fail()) {
		cout << "fail change!" << endl;
	}

	if (cin.bad()) {
		cout << "bad change!" << endl;
	}

	if (cin.good()) {
		cout << "good change" << endl;
	}
}

位状态的具体运用:
int main() {
	auto old_state = cin.rdstate();  //记住cin当前状态
	cin.clear();   //所有位复位 使操作有效
	
	TestIstreamRight();  //使用cin
	CheckBit();

	cin.setstate(old_state);  //恢复到初始状态

	//手动复位
	cout << endl << "after setState:" << endl;

	cin.clear(cin.rdstate() & ~cin.failbit & ~cin.badbit);  //手动复位 ~表示位求反 将failbit位和badbit位恢复
	CheckBit();

	system("PAUSE");
	return 0;
}






















你可能感兴趣的:(C/C++)