• C++之IO流


    C语言的输入与输出

    在C语言当中,我们使用最频繁的输入输出方式就是scanf与printf:

    • scanf: 从标准输入设备(键盘)读取数据,并将读取到的值存放到某一指定变量当中。
    • printf: 将指定的数据输出到标准输出设备(屏幕),使用时需要注意宽度输出和精度输出的控制。

    C语言借助了相应的缓冲区来进行输入与输出,如下图所示:
    在这里插入图片描述
    对输入输出缓冲区的理解:

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

    流是什么

    “流”即是流动的意思,是物质从一处向另一处流动的过程,是对一种有序连续且具有方向性的数据( 其单位可以是bit,byte,packet )的抽象描述。

    C++流是指信息从外部输入设备(如键盘)向计算机内部(如内存)输入和从内存向外部输出设备(显示器)输出的过程。这种输入输出的过程被形象的比喻为“流”。

    它的特性是:有序连续、具有方向性。

    C++IO流

    C++系统实现了一个庞大的类库,其中ios为基类,其他类都是直接或间接派生自ios类。
    在这里插入图片描述

    C++标准IO流

    C++标准库提供了4个全局流对象(cin、cout、cerr、clog):

    • 使用cout进行标准输出,即数据从内存流向控制台(显示器)。
    • 使用cin进行标准输入,即数据通过键盘输入到程序中。
    • 使用cerr进行标准错误的输出。
    • 使用clog进行日志的输出。

    从上图可以看出,cout、cerr、clog都是由ostream类实例化出的三个不同的对象,因此这三个对象基本没什么区别,只是应用场景不同。

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

    注意

    1. cin为缓冲流。键盘输入的数据保存在缓冲区中,当要提取时,是从缓冲区中拿。如果一次输入过多,会留在那儿慢慢用,如果输入错了,必须在回车之前修改,如果回车键按下就无法挽回了。只有把输入缓冲区中的数据取完后,才要求输入新的数据;
    2. 输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对应位置(位置1),程序继续;
    3. 空格和回车都可以作为数据之间的分格符,所以多个数据可以在一行输入,也可以分行输入。但如果是字符型和字符串,则空格(ASCII码为32)无法用cin输入,字符串中也不能有空格。回车符也无法读入。
    4. cin和cout可以直接输入和输出内置类型数据,原因:标准库已经将所有内置类型的输入和输出全部重载了:
      在这里插入图片描述
    5. 对于自定义类型,如果要支持cin和cout的标准输入输出,需要对<<和>>进行重载。

    比如下面的日期类:

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    1. 在线OJ中的输入和输出:
    • 对于IO类型的算法,一般都需要循环输入;
    • 输出:严格按照题目的要求进行,多一个少一个空格都不行;
    • 连续输入时,vs系列编译器下在输入ctrl+Z时结束。
    // 单个元素循环输入
    while(cin>>a)
    {
    // ...
    }
    // 多个元素循环输入
    while(c>>a>>b>>c)
    {
    // ...
    }
    // 整行接收
    while(cin>>str)
    {
    // ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    C++文件IO流

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

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

    操作文件的类有以下三个:

    对应操作场景
    ofstream只写
    ifstream只读
    fstream读+写
    1. 使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系。
      文件常见的打开方式如下:
    打开方式功能
    in以读的方式打开文件
    out以写的方式打开文件
    binary以二进制方式对文件进行操作
    ate输出位置从文件的末尾开始
    app以追加的方式对文件进行写入
    trunc先将文件内容清空再打开文件
    1. 使用提取和插入运算符对文件进行读写操作,或使用成员函数进行读写。

    对文件进行提取和插入操作的常用成员函数:

    成员函数功能
    put插入一个字符到文件
    write插入一段字符到文件
    get从文件提取字符
    read从文件提取多个字符
    tellg获取当前字符在文件当中的位置
    seekg设置对文件进行操作的位置
    << 运算符重载将数据形象地以“流”的形式进行输出
    >> 运算符重载将数据形象地以“流”的形式进行输入
    1. 关闭文件。
    #include 
    #include 
    using namespace std;
    
    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() const
    	{
    		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 ServerInfo
    {
    	char _address[32];
    	int _port;
    	Date _date;
    };
    
    struct ConfigManager
    {
    public:
    	ConfigManager(const char* filename)
    		:_filename(filename)
    	{}
    
    	// 二进制读写,读写对象中,不能有string
    	void WriteBin(const ServerInfo& info)
    	{
    		ofstream ofs(_filename, ofstream::out | ofstream::binary);
    		ofs.write((char*)&info, sizeof(info));
    	}
    
    	void ReadBin(ServerInfo& info)
    	{
    		ifstream ifs(_filename, ofstream::in | ofstream::binary);
    		ifs.read((char*)&info, sizeof(info));
    	}
    
    	// 文本读写 C++文本读写更简单
    	// 文本读写本质,内存中任何类型都是转成字符串在写
    	// c语言文本读写很不方便,因为要不断转字符串
    	// c++封装了以后就有很大的优势
    	void WriteText(const ServerInfo& info)
    	{
    		ofstream ofs(_filename);
    		ofs << info._address << " ";
    		ofs << info._port << endl;
    		ofs << info._date << endl;
    	}
    
    	void ReadText(ServerInfo& info)
    	{
    		ifstream ifs(_filename);
    		ifs >> info._address;
    		ifs >> info._port;
    		ifs >> info._date;
    	}
    
    private:
    	string _filename; // 配置文件
    };
    
    int main()
    {
    	ServerInfo winfo = { "192.0.0.1", 80, { 2023, 7, 11 } };
    
    	string str;
    	cin >> str;
    	if (str == "二进制写")
    	{
    		ConfigManager cm("test.txt");
    		cm.WriteBin(winfo);
    	}
    	else if (str == "二进制读")
    	{
    		ServerInfo rinfo;
    		ConfigManager cm("test.txt");
    		cm.ReadBin(rinfo);
    		cout << rinfo._address << endl;
    		cout << rinfo._port << endl;
    		cout << rinfo._date << endl;
    	}
    	else if (str == "文本写")
    	{
    		ConfigManager cm("test.txt");
    		cm.WriteText(winfo);
    	}
    	else if (str == "文本读")
    	{
    		ServerInfo rinfo;
    		ConfigManager cm("test.txt");
    		cm.ReadText(rinfo);
    
    		cout << rinfo._address << endl;
    		cout << rinfo._port << endl;
    		cout << rinfo._date << endl;
    	}
    	
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131

    stringstream的介绍

    在C语言中,我们若是想要将一个整型变量的数据转化为字符串格式,有以下两种方法:
    1、使用itoa函数进行转化。

    	int a = 10;
    	char arr[10];
    	itoa(a, arr, 10);
    
    • 1
    • 2
    • 3

    2、使用sprintf函数进行转化。

    int a = 10;
    char arr[10];
    sprintf(arr, "%d", a); 
    
    
    • 1
    • 2
    • 3
    • 4

    虽然itoa函数和sprintf函数都能完成转化,但是在两个函数在转化时,都需要先给出保存结果的空间,而空间的大小是不太好界定的,除此之外,转化格式不匹配时,可能还会得到错误的结果甚至程序崩溃。

    在C++中,我们可以使用stringstream类对象来避开此问题。在程序当中如果想要使用stringstream,必须要包含头文件sstream。在该头文件下,有三个类:

    对应操作场景
    ostringstream输出操作
    istringstream输入操作
    stringstream输入操作+输出操作
    #include 
    
    int main()
    {
    	stringstream oss;
    	oss << 100 << " ";
    	oss << 11.22 << " ";
    	oss << "hello";
    
    	string str = oss.str();
    	cout << str << endl;
    
    	stringstream iss(str);
    	int i;
    	double d;
    	string s;
    	iss >> i >> d >> s;
    	cout << i << endl;
    	cout << d << endl;
    	cout << s << endl;
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    序列化与反序列化

    struct ChatInfo
    {
    	string _name; // 名字
    	int _id;      // id
    	Date _date;   // 时间
    	string _msg;  // 聊天信息
    };
    
    int main()
    {
    	ChatInfo winfo = { "张三", 135246, { 2022, 4, 10 }, "晚上一起看电影吧" };
    	stringstream oss;
    	oss << winfo._name << " ";
    	oss << winfo._id << " ";
    	oss << winfo._date << " ";
    	oss << winfo._msg;
    	string str = oss.str();
    	cout << str << endl;
    
    	stringstream iss(str);
    	ChatInfo rinfo;
    	iss >> rinfo._name;
    	iss >> rinfo._id;
    	iss >> rinfo._date;
    	iss >> rinfo._msg;
    
    	cout << "-------------------------------------------------------" << endl;
    	cout << "姓名:" << rinfo._name << "(" << rinfo._id << ") ";
    	cout << rinfo._date << endl;
    	cout << rinfo._name << ":>" << rinfo._msg << endl;
    	cout << "-------------------------------------------------------" << endl;
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
  • 相关阅读:
    freeRTOS学习day4-中断使用消息队列
    HashMap与HashSet
    C# 利用.NET 升级助手将.NET Framework项目升级为.NET 6
    MySQL学习笔记(一 mysql简介)
    【微信小程序】项目初始化
    【Redis】常用命令介绍
    使用Spring Data Elasticsearch 进行索引的增、删、改、查
    警惕国外科技断供风险:CACTER邮件网关信创一体机为商业银行提供全国产化防护
    07 Spring事务
    Linux TC 流量控制介绍
  • 原文地址:https://blog.csdn.net/2303_77100822/article/details/133858401