[C++] Input and output stream (IO stream)


1. Input and output of C language

The most commonly used input and output methods in C language are scanf() and printf(). scanf() is to read data from the standard input device (keyboard) and store the value in one or some variables; printf() is to output the specified text/string to the standard output device (screen) .

C language uses corresponding buffers for input and output. As shown below:

insert image description here

Understanding of input and output buffers:

  1. The implementation of low-level IO can be shielded. The implementation of low-level IO generally depends on the implementation of the operating system kernel. If this part of the difference can be shielded, portable programs can be easily written.
  2. The behavior of "line" reading can be realized. For computers, there is no concept of "line", but with this part, the concept of "line" can be defined, and then the content of the buffer can be parsed to return a "line" ".

2. What is flow

"Flow" means flow, the process by which matter flows from one place to another. Specifically, it is an abstract description of an ordered, continuous and directional data (the unit can be bit, byte, packet).

C++ stream refers to the process of inputting information from external input devices (such as keyboard) to the internal computer (such as memory) and outputting from memory to external output devices (displays). This input and output process is vividly likened to "flow".

Its characteristics are: orderly, continuous, and directional

In order to realize this kind of flow, C++ defines the I/O standard class library. Each of these classes is called a flow or a flow class, which is used to complete a certain function. These flows will be introduced below.


Three, C++ IO stream

1. Overview

The C++ system implements a huge library of classes, as shown in the figure below. Among them, ios is the base class, and other classes are directly or indirectly derived from the ios class.
insert image description here


2. Standard IO stream

(1)cin、cout、cerr、clog

The C++ standard library provides four global stream objects cin, cout, cerr, and clog. Use cout for standard output, that is, data flows from memory to the console (display); use cin for standard input, that is, data is entered into the program through the keyboard; use cerr for standard error output; use clog for log output.

As can be seen from the previous figure, cout, cerr, and clog are three different objects of the ostream class, so these three objects are basically the same, but the application scenarios are different.

As shown in the figure below, they are all output to the display. The original intention is to use cout for general output, cerr for error output, and clog for log output, but generally the latter two are rarely used, and cout is used for all output.

The results are as follows:
insert image description here


(2) cin, cout and scanf, printf

C++ provides cin, cout, C language provides scanf, printf, they can both input and output, but it is recommended to use cin and cout first, if you encounter formatted input and output, use scanf, printf (cin , cout can also format input and output, but it is more complicated to use, it is better to directly use the ready-made scanf, printf).

At the same time, because C++ is quite different from C language in some aspects, sometimes there will be problems in mixing four inputs and outputs.

For example, the string string uses the size value to mark the end of the string in C++, while the C language uses '\0' to mark the end of the string. This difference may cause problems during input and output. For this reason, string also c_str() is specially provided for operations in the C language.


(3) Input and output overloading

Cin and cout can directly input and output built-in types (such as int, double, etc.) and some standard custom types (such as string, etc.), because the standard library has overloaded the input and output of all these types, and can be used directly .

insert image description here

For our custom types, if we want to use cin and cout directly for input and output, we need to overload >> and << by ourselves, otherwise we cannot use them directly.


(4)getline

Like scanf, cin also divides data with spaces and line breaks, so for a line of data with spaces, it cannot read all the data. In this case, getline is used, and getline divides data with line breaks, as shown in the following figure. .

The results are as follows:
insert image description here


(5) Loop input

When entering several lines of content, the following solutions can be used.

The results are as follows:
insert image description here
similar to the C language:

char buffer[100];
while(scanf("%s", buffer) != EOF)
{
    
    
	//...
}

You can use Ctrl+C to end the input. Its essence is to send a signal to the process. For details, you can see the process signal of [Ten Thousand Characters Detailed Linux Series] , which is the same under Linux and Windows.


2. File stream fstream

(1) ifstream 、 ofstream

ifstream creates an object as follows, where name is the filename and mode is the mode of operation.

ifstream ifs(name, mode);

There are the following modes to choose from:

insert image description here

The member functions that can be called by the ifstream object are commonly used get, getline, read, seekg, tellg, etc. You can get a general idea of ​​what it does by looking at the function name. get gets the file one character at a time, getline gets the file one line at a time, read reads a piece of content from the file, seekg sets the position of the file pointer, and tellg finds the position of the file pointer.


(2) Usage

  1. Define a file stream object: ifstream (for input only), ofstream (for output only), fstream (for both input and output)
  2. Use the member function of the file stream object to open a disk file to establish a relationship between the file stream object and the disk file
  3. Read and write operations to files using extract and insert operators, or member functions to read and write
  4. close file

Similar to C language usage

The following two pieces of code respectively demonstrate ifstream and ofstream reading and writing files. The writing method is similar to the interfaces of fread and fwrite in C language, but it has become object-oriented.

The following code uses ifstream to read the contents of the file.

The results are as follows:
insert image description here


The following code is to use ofstream to write content to the file, the usage method is basically the same as ifstream.

The results are as follows:
insert image description here


Usage of C++

The following is a new usage of the file stream provided by C++. The file stream is also a stream, so he can also use << or >> to read and write. The usage is as follows.

code show as below:

void WriteFile()
{
    
    
	//类似于C语言的用法
	//ofstream ofs("write.txt");
	//ofs.put('h');
	//char msg[] = "ello world";
	//int size = sizeof(msg);
	//ofs.write(msg, size);
	//可调可不调,因为ofs出了作用域后析构函数会自动调用
	//ofs.close();

	//C++的新用法
	ofstream ofs("write.txt");
	char c = 'h';
	string str = "ello world";

	ofs << c << str;
}

int main()
{
    
    
	WriteFile();
	return 0;
}

In this way, the ofstream object can also write content to the file through the stream like cout.

The results are as follows:
insert image description here

The use of ifstream is the same, but the direction of the stream should be reversed, so I won't go into details here.


3. String stream sstream

sstream includes istringstream, ostringstream and stringstream, which are used for stream input, output and input and output operations, but it is generally more convenient to use stringstream directly.

(1) read

code show as below:

#include <sstream>
#include <iostream>

using namespace std;

struct ServerInfo//一个简单的结构体
{
    
    
	string ip;
	int port;
};

int main()
{
    
    
	stringstream ss;//定义一个对象
	ServerInfo info = {
    
     "192.0.0.1",8081 };//初始化

	ss << info.ip << " "  << info.port;//将info的两个成员流入ss
	string str = ss.str();//通过成员函数str()拿到ss内存储的字符串
	cout << str << endl;//打印

	return 0;
}

The running result is as follows, the processing of strings is very convenient.

The results are as follows:
insert image description here


(2) write

Write the read content to the new structure based on the previous read.

code show as below:

#include <sstream>
#include <iostream>

using namespace std;

struct ServerInfo
{
    
    
	string ip;
	int port;
};

int main()
{
    
    
	stringstream ss;
	ServerInfo info = {
    
     "192.0.0.1",8081 };

	ss << info.ip << " " << info.port;
	
	//将s中的内容又写入newInfo中
	//注意:不同项的内容必须以空格或换行结尾,这是C/C++都要求的
	ServerInfo newInfo;
	ss >> newInfo.ip >> newInfo.port;

	return 0;
}

The results are as follows:

insert image description here


Thanks for reading, if there are any mistakes, please criticize and correct

Guess you like

Origin blog.csdn.net/weixin_51983604/article/details/124293916