C++之IO流

目录

一、C语言的输入与输出

二、流是什么

三、C++IO流

3.1、C++标准IO流

3.2、C++文件IO流

四、stringstream的简单介绍


一、C语言的输入与输出

C语言中我们用到的最频繁的输入输出方式就是scanf ()与printf()。 scanf(): 从标准输入设备(键盘)读取数据,并将值存放在变量中。printf(): 将指定的文字/字符串输出到标准输出设备(屏幕)。 注意宽度输出和精度输出控制。C语言借助了相应的缓冲区来进行输入与输出。如下图所示:

对输入输出缓冲区的理解:

  1. 可以屏蔽掉低级I/O的实现,低级I/O的实现依赖操作系统本身内核的实现,所以如果能够屏 蔽这部分的差异,可以很容易写出可移植的程序。
  2. 可以使用这部分的内容实现“行(hang)”读取的行为,对于计算机而言是没有“行”这个概念,有了这部分,就可以定义“行”的概念,然后解析缓冲区的内容,返回一个“行”。

二、流是什么

  • “流”即是流动的意思,是物质从一处向另一处流动的过程,是对一种有序连续且具有方向性的数据( 其单位可以是bit,byte,packet )的抽象描述。
  • C++流是指信息从外部输入设备(如键盘)向计算机内部(如内存)输入和从内存向外部输出设备(显示器)输出的过程。这种输入输出的过程被形象的比喻为“流”。
  • 它的特性是:有序连续、具有方向性
  • 为了实现这种流动,C++定义了I/O标准类库,这些每个类都称为流/流类,用以完成某方面的功能。

三、C++IO流

C++系统实现了一个庞大的类库,其中ios为基类,其他类都是直接或间接派生自ios类。

3.1、C++标准IO流

C++标准库提供了4个全局流对象cin、cout、cerr、clog,使用cout进行标准输出,即数据从内存流向控制台(显示器)。使用cin进行标准输入即数据通过键盘输入到程序中,同时C++标准库还提供了cerr用来进行标准错误的输出,以及clog进行日志的输出,从上图可以看出cout、cerr、clog是ostream类的三个不同的对象,因此这三个对象现在基本没有区别,只是应用场景不同。

如图:

在使用时候必须要包含文件并引入std标准命名空间。

注意:

1. cin为缓冲流。键盘输入的数据保存在缓冲区中,当要提取时,是从缓冲区中拿。如果一次输入过多,会留在那儿慢慢用,如果输入错了,必须在回车之前修改,如果回车键按下就无法挽回了。只有把输入缓冲区中的数据取完后,才要求输入新的数据。

2. 空格和回车都可以作为数据之间的分格符,所以多个数据可以在一行输入,也可以分行输入。但如果是字符型和字符串,则空格(ASCII码为32)无法用cin输入,字符串中也不能有空格。回车符也无法读入。

3. cin和cout可以直接输入和输出内置类型数据,原因:标准库已经将所有内置类型的输入和输出全部重载了。如图:

4.  对于自定义类型,如果要支持cin和cout的标准输入输出,需要对和>>进行重载。

5. istream类型对象转换为逻辑条件判断值

istream& operator>> (int& val);

explicit operator bool() const;

实际上我们看到使用while(cin>>i)去流中提取对象数据时,调用的是operator>>,返回值是istream类型的对象,那么这里可以做逻辑条件值,源自于istream的对象又调用了operator bool,operator bool调用时如果接收流失败,或者有结束标志,则返回false。

6. 在线OJ中的输入和输出:

  • 对于IO类型的算法,一般都需要循环输入:
  • 输出:严格按照题目的要求进行,多一个少一个空格都不行。

连续输入时,vs系列编译器下在输入ctrl+Z时结束

示例代码:

解释:首先我们需要了解为什么cin读取后的返回值可以作为while循环的判断条件,cin读取后的返回值其实是一个istream类型,这里其实是利用返回值调用了istream类中重载的bool类型,如下:

while(cin>>ch)  ->  while (operator>>(cin, ch).operator bool())

通过将返回值转化为bool值,进而判断是否继续读取。那么是如何判断转化的bool值是true还是false的呢?其实IO流设置了四个标志,这四个标志用一个整型值来存储,像位图那样,不同位置为0还是为1代表了某一个标志位是否被设置。标志如图:

其中,eofbit被设置代表读取到文件末尾,failbit被设置代表读取过程中出现问题,但问题不大,通过重置标志位可继续读取,badbit被设置代表istream流出现了大问题,可能是溢出或者别的问题,当前流已经不可用了,goodbit被设置代表正常读取。istream流中有四个方法,分别可以获取对应标志位是否被设置,如果被设置,方法返回true,否则false。如图:

示例代码一:

int main()
{
	string str;
	//先看一下没有读取时标志位如何
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	// istream& operator>> (istream& is, string& str);
	//while (cin >> str)
	while (operator>>(cin, str).operator bool())
	{
		cout << cin.good() << endl;
		cout << cin.eof() << endl;
		cout << cin.bad() << endl;
		cout << cin.fail() << endl << endl;

		cout << str << endl;			
	}

	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	return 0;
}

效果:

解释:从图中看可以看出,最开始只有goodbit被设置,也只有当goodbit被设置时可以正常读取,当我们输入Ctrl+Z和换行时,eofbit,failbit被设置,程序因此停止。

示例代码二:

int main()
{
	string str;
	//先看一下没有读取时标志位如何
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	// istream& operator>> (istream& is, string& str);
	//while (cin >> str)
	while (operator>>(cin, str).operator bool())
	{
		cout << cin.good() << endl;
		cout << cin.eof() << endl;
		cout << cin.bad() << endl;
		cout << cin.fail() << endl << endl;

		cout << str << endl;			
	}

	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	while (cin >> str)
	{
		cout << cin.good() << endl;
		cout << cin.eof() << endl;
		cout << cin.bad() << endl;
		cout << cin.fail() << endl << endl;

		cout << str << endl;
	}

	return 0;
}

效果:

解释:从上面图中可以看出,当我们将标志位通过某种方式设置为不可读取后,即使后面还有读取操作,也会因为标记位被设置而无法读取。如果我们想让后面能够继续读取就需要重置标记位。方法如下图。

示例代码三:

int main()
{
	string str;
	//先看一下没有读取时标志位如何
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	// istream& operator>> (istream& is, string& str);
	//while (cin >> str)
	while (operator>>(cin, str).operator bool())
	{
		cout << cin.good() << endl;
		cout << cin.eof() << endl;
		cout << cin.bad() << endl;
		cout << cin.fail() << endl << endl;

		cout << str << endl;			
	}

	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	// 恢复标志状态
	cin.clear();

	while (cin >> str)
	{
		cout << cin.good() << endl;
		cout << cin.eof() << endl;
		cout << cin.bad() << endl;
		cout << cin.fail() << endl << endl;

		cout << str << endl;
	}

	return 0;
}

注意:Ctrl+C和Ctrl+Z是不同的,Ctrl+C是发送信号将进程杀掉,而Ctrl+Z是设置标记位,使循环读取结束。

7. 输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对应位置位(置1),程序继续。

示例代码:

int main()
{
	int i = 0;
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	cin >> i;
	cout << i << endl;

	// 11sss
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;
}

效果:

解释:从图中可以看出当读取数据类型与需要的类型不一致时,failbit被设置,同时这里因为读取失败,将 i 置为了0。

解决方法:

int main()
{
	int i = 0;
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	cin >> i;
	cout << i << endl;

	// 11sss
	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	cin >> i;
	cout << i << endl;
	if (cin.fail())
	{
		cin.clear();
		char ch;
		while (cin.get(ch))
		{
			cout << ch;
		}
	}

	cin >> i;
	cout << i << endl;

	cout << cin.good() << endl;
	cout << cin.eof() << endl;
	cout << cin.bad() << endl;
	cout << cin.fail() << endl << endl;

	return 0;
}

3.2、C++文件IO流

C++根据文件内容的数据格式分为二进制文件和文本文件。采用文件流对象操作文件的一般步 骤:

1. 定义一个文件流对象:

  • ifstream ifile(只输入用)
  • ofstream ofile(只输出用)
  • fstream iofile(既输入又输出用)

2. 使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系。

3. 使用提取和插入运算符对文件进行读写操作,或使用成员函数进行读写。

4. 关闭文件。

示例代码一:

#include<fstream>

int main()
{
	//两种打开文件方式
	//可以在构造时打开
	//也可以调用open方法
	ofstream ofs("test.txt");
	//ofs.open("test.txt");

	//三种写入方式
	ofs.put('x');
	ofs.write("hello\n", 6);
	//重载<< 这种方式好用
	ofs << "22222222" << endl;

	int x = 111;
	double y = 1.11;
	ofs << x << endl;
	ofs << y << endl;

	//关闭文件
	// 可以显式调用close关闭
	// 也可以不管,它会自动关闭,因为C++中将其封装为类
	// 它有析构,生命周期到了自动释放
	//ofs.close();

	return 0;
}

示例代码二:(统计二进制文件的字符个数)

int main()
{
	//ifstream ofs("test.cpp");
	ifstream ofs("D:\\360MoveData\\Users\\xjh\\Desktop\\8-10.png", ios_base::in | ios_base::binary);

	int n = 0;
	while (!ofs.eof())
	{
		char ch = ofs.get();
		//cout << ch;
		++n;
	}

	cout << n << endl;

	return 0;
}

示例代码三:

struct ServerInfo
{
	//char _address[32];
	string _address;

	int _port;

	//Date为自己封装的类
	Date _date;
};

解释:上面代码为一个结构化数据,其中有一个成员变量是string类型的,当string数据足够大时,它的数据是存在堆上的,string本身只会存储一个指向这块堆空间的指针,这时写入数据就只会写入该指针,当我们去读的时候就会造成非法访问,因为写的进程可能已经结束了,这块堆空间已经释放了。所以对于这种自定义类型进行文件操作时需要注意,我们要写的是内容,而不是指针。

四、stringstream的简单介绍

在C语言中,如果想要将一个整形变量的数据转化为字符串格式,如何去做?

  1. 使用itoa()函数
  2. 使用sprintf()函数

示例代码:

int main()
{
	int n = 123456789;
	char s1[32];
	_itoa(n, s1, 10);
	char s2[32];
	sprintf(s2, "%d", n);
	char s3[32];
	sprintf(s3, "%f", n);
	return 0;
}

但是两个函数在转化时,都得需要先给出保存结果的空间,那空间要给多大呢,就不太好界定, 而且转化格式不匹配时,可能还会得到错误的结果甚至程序崩溃。

在C++中,可以使用stringstream类对象来避开此问题。在程序中如果想要使用stringstream,必须要包含头文件。在该头文件下,标准库三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。

stringstream主要可以用来:

1. 将数值类型数据格式化为字符串

int main()
{
	int a = 12345678;
	string sa;
	// 将一个整形变量转化为字符串,存储到string类对象中

	stringstream s;
	s << a;
	s >> sa;
	// clear()

	// 注意多次转换时,必须使用clear将上次转换状态清空掉

	// stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit

	// 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换

	// 但是clear()不会将stringstreams底层字符串清空掉

	// s.str("");

 // 将stringstream底层管理string对象设置成"", 

 // 否则多次转换时,会将结果全部累积在底层string对象中


	s.str("");
	s.clear();   // 清空s, 不清空会转化失败

	double d = 12.34;
	s << d;
	s >> sa;
	string sValue;
	sValue = s.str();  // str()方法:返回stringsteam中管理的string类型

	cout << sValue << endl;
	return 0;
}

2. 字符串拼接

int main()
{
	stringstream sstream;
	// 将多个字符串放入 sstream 中

	sstream << "first" << " " << "string,";
	sstream << " second string";
	cout << "strResult is: " << sstream.str() << endl;
	// 清空 sstream

	sstream.str("");
	sstream << "third string";
	cout << "After clear, strResult is: " << sstream.str() << endl;
	return 0;
}

3. 序列化和反序列化结构数据

class Date
{
	friend ostream& operator << (ostream& out, const Date& d);
	friend istream& operator >> (istream& in, Date& d);
public:
	Date(int year = 1, int month = 1, int day = 1)
		:_year(year)
		, _month(month)
		, _day(day)
	{}
	operator bool()
	{
		// 这里是随意写的,假设输入_year为0,则结束
		if (_year == 0)
			return false;
		else
			return true;
	}
private:
	int _year;
	int _month;
	int _day;
};

istream& operator >> (istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;
	return in;
}

ostream& operator << (ostream& out, const Date& d)
{
	out << d._year << " " << d._month << " " << d._day;
	return out;
}

struct ChatInfo

{
	string _name; // 名字
	int _id;      // id
	Date _date;   // 时间
	string _msg;  // 聊天信息

};

int main()
{
	// 结构信息序列化为字符串

	ChatInfo winfo = { "张三", 135246, { 2022, 4, 10 }, "晚上一起看电影吧"
	};
	ostringstream oss;
	oss << winfo._name << " " << winfo._id << " " << winfo._date << " "

		<< winfo._msg;
	string str = oss.str();
	cout << str << endl << endl;
	// 我们通过网络这个字符串发送给对象,实际开发中,信息相对更复杂,

	   // 一般会选用Json、xml等方式进行更好的支持

	// 字符串解析成结构信息

	ChatInfo rInfo;
	istringstream iss(str);
	iss >> rInfo._name >> rInfo._id >> rInfo._date >> rInfo._msg;
	cout << "-------------------------------------------------------"

		<< endl;
	cout << "姓名:" << rInfo._name << "(" << rInfo._id << ") ";
	cout << rInfo._date << endl;
	cout << rInfo._name << ":>" << rInfo._msg << endl;
	cout << "-------------------------------------------------------"

		<< endl;
	return 0;
}

istringstream,ostringstream使用示例代码:

int main()
{
	int i = 123;
	Date d = { 2022, 4, 10 };
	ostringstream oss;
	oss << i << endl;
	oss << d << endl;

	string s = oss.str();
	cout << s << endl;

	//istringstream iss(s);
	//istringstream iss;
	//iss.str("100 2024 9 9");
	istringstream iss("100 2024 9 9");
	int j;
	Date x;
	iss >> j >> x;

	return 0;
}

注意:

1. stringstream实际是在其底层维护了一个string类型的对象用来保存结果。

2. 多次数据类型转化时,一定要用clear()来清空,才能正确转化,但clear()不会将stringstream底层的string对象清空。

3. 可以使用s. str("")方法将底层string对象设置为""空字符串。

4. 可以使用s.str()将让stringstream返回其底层的string对象。

5. stringstream使用string类对象代替字符数组,可以避免缓冲区溢出的危险,而且其会对参数类型进行推演,不需要格式化控制,也不会出现格式化失败的风险,因此使用更方便,更安全。

评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值