Classification of Streams in C++

foreword

The question about the nature of streams has actually existed since I first started learning C++. At that time, I found a lot of information, but I was always in the state of knowing it but not knowing why. I still haven't figured out the essence of flow, and I have always been ignorant.
But today, when I was looking up stream-related information on a whim, I suddenly found that I seemed to understand it, so I used this blog to record it.
One thing needs to be stated in advance. The following content is my own understanding. Due to the accumulation of personal knowledge and experience, there may be some deficiencies. If you find any mistakes, please correct them.

flow understanding

The essence of a stream is an object .

A stream is an intermediate device between data and programs .

Because of the existence of streams, we do not need to directly manipulate data, but indirectly manipulate data by manipulating streams.

stream advantage

Uniform operating standards.

No matter what kind of data and the type of data, as long as the data is associated with the stream, then we don't need to consider how the data is stored, and only need to operate according to the operating standard of the stream. This is unity operating standards.

As mentioned above, the essence of a stream is an object, so there are many methods for streams. These methods provide us with a unified interface for operating data, and we can even operate without changing the code. different data.

Classification of Streams in C++

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-0KxVaOJC-1686041257286) (C:\Users\hp\AppData\Roaming\Typora\typora-user-images\ image-20230417223450379.png)]

C++ middle streams are mainly divided into three categories:

  • IO stream: input and output stream, iostream
  • File stream: For file operations, fstream
  • String stream: mainly implements operations on strings, stringstream

I流

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-6YJmhysV-1686041257287) (C:\Users\hp\AppData\Roaming\Typora\typora-user-images\ image-20230417223559721.png)]

These three are still the same in essence, they are all abstract methods, but the objects of operation are different. The relationship diagram between these classes is posted below:

insert image description here

It can be seen from the above figure why it is said that fstream can be used in the same way as cin/cout, because fstream itself is inherited from iostream.

string stream sstream

basic concept

Use string type variables in memory as input and output objects..
Features:

  • Same as the standard input and output stream, it can convert between text and binary.
  • Save data to string ⇔ \Leftrightarrow⇔cout convert binary to ASCII.
  • Get data from string ⇔ \Leftrightarrow⇔cin ASCII to binary.
  • No need to open and close.
  • Can store various types of data.

use

#include <sstream>
ostringstream ostr;//输出流
istringstream istr;//输入流
stringstream str;//输入/输出流

The sstring header file defines three types to support memory IO operations. These types can write data to string and read data from string, just like string is an IO stream.

istringstream reads data from string, ostringstream writes data to string, and stringstream can both write data to string and read data to string.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-u0qXk7ik-1686041257289) (C:\Users\hp\AppData\Roaming\Typora\typora-user-images\ image-20230417221021687.png)]

#pragma once
#include<iostream>
#include<sstream>
#include<string>

class Stream {
public:
	Stream() {}
	Stream(std::string& str)
		:str_(str)
	{}
	~Stream() {};

	//输出流
	void OsStringStream();
	//输入流
	void IsStringStream();
	//输入输出流
	void StringStringStream();

protected:
	std::string str_;
};

#include"stream.h"

void Stream::OsStringStream() {
	std::ostringstream oss(str_);
	std::cout << oss.str() << std::endl;
}

void Stream::IsStringStream() {
	std::string line;
	std::istringstream iss(str_);
	std::getline(iss, line);
	std::cout << line << std::endl;

	//创建输入流
	std::istringstream str;
	//拷贝字符串到输入流中
	str.str("bye bye");
	//用str_str返回str.str()的拷贝
	std::string str_str = str.str();
	std::cout << str_str << std::endl;
}

void Stream::StringStringStream() {
	std::stringstream ss1(str_);
	std::cout << ss1.str() << std::endl;
}

#include"stream.h"

int main() {
	std::string str("ni hao");
	Stream stream(str);
	stream.IsStringStream();
	stream.OsStringStream();
	stream.StringStringStream();
	return 0;
}

file stream fstream

img

When the program is running, the generated data is temporary data, and will be released once the program finishes running, and the data can be persisted through the file. C++ needs to include the header file < fstream > for file operations. There are two types of text:

(1) Text file: The file is stored in the computer in the form of ASCII code of text.
(2) Binary files: Files are stored in the computer in the binary form of text, and users generally cannot read them directly.

Three categories of operating files:

  • ofstream: write

  • ifstream: read

  • fstream: read and write

text file

write file

Proceed as follows:

  • Include header files: #include<fstream>
  • Create a stream object: ofstream ofs;
  • Open the file: ofs.open("file path", open method);
  • Write data: ofs<<"written data";
  • Close the file: ofs.close();

Open method:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-yhqK8uDz-1686041257289) (C:\Users\hp\AppData\Roaming\Typora\typora-user-images\ image-20230417223237070.png)]

insert image description here

Note: The file opening method can be used in conjunction with the | operator.

void Csv::WriteCsvFile() {
	//std::ofstream out_file("data.csv", std::ios::out); //std::ios::out 文件不存在则创建文件,有文件则清空文件
	std::ofstream out_file;
	out_file.open("data.csv", std::ios::out);
	if (!out_file) {
		std::cout << "open file failed" << std::endl;
		return;
	}
	for(int i = 0; i < 5; ++i) {
		out_file << 12 << ",";
		out_file << 13 << ",";
		out_file << 14 << std::endl;
	}
	out_file.close();
	std::cout << "write file successed" << std::endl;
}

insert image description here

read file

Proceed as follows:

  • Include header files: #include<fstream>
  • Create a stream object: ifstream ifs;
  • Open the file and judge whether the file is opened successfully: ifs.open("file path", open method);
  • Reading data: four reading methods
  • Close the file: ifs.close();

insert image description here

insert image description here

#pragma once
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>

class Csv {
public:
	Csv() {}
	~Csv() {}
	void ReadCsvFile();
	void WriteCsvFile();
};

#include"csv.h"

void Csv::ReadCsvFile() {
	//std::ifstream in_file("data.csv", std::ios::in);
	std::ifstream in_file;
	in_file.open("data.csv", std::ios::in);
	if (!in_file) {
		std::cout << "open fill failed" << std::endl;
	}
	int num = 0;
	std::string line;
	std::string file;
	while (std::getline(in_file, line)) {
		std::string file;
		// 将整行字符串line读入到字符串流iss中
		std::istringstream iss(line);
		std::getline(iss, file, ',');
		//将刚刚读取的字符串转换成int
		std::cout << std::atoi(file.c_str()) << " ";
		std::getline(iss, file, ',');
		std::cout << std::atoi(file.c_str()) << " "; 
		std::getline(iss, file, ',');
		std::cout << std::atoi(file.c_str()) << std::endl;
		num++;
	}
	std::cout << "读取了" << num << "行" << std::endl;
	if (5 == num) {
		std::cout << "read file success" << std::endl;
	}
	in_file.close();
}

void Csv::WriteCsvFile() {
	//std::ofstream out_file("data.csv", std::ios::out);
	std::ofstream out_file;
	out_file.open("data.csv", std::ios::out);
	if (!out_file) {
		std::cout << "open file failed" << std::endl;
		return;
	}
	for(int i = 0; i < 5; ++i) {
		out_file << 12 << ",";
		out_file << 13 << ",";
		out_file << 14 << std::endl;
	}
	out_file.close();
	std::cout << "write file successed" << std::endl;
}

#include"csv.h"

int main() {
	Csv csv;
	csv.WriteCsvFile();
	csv.ReadCsvFile();
	return 0;
}

Each file stream has a default file mode, the file associated with ifstream is opened in mode by default, the file associated with ofstream is opened in out mode by default, and the file associated with fstream is opened in and out mode by default.

ofstream out; // 未指定文件打开模式
out.open("test.txt"); // 模式隐含设置为输出和截断
out.close(); // 关闭out
out.open("test2.txt",ofstream::app); //模式为输出和追加
out.close(); //关闭out 

Guess you like

Origin blog.csdn.net/qq_44918090/article/details/131071216