7-1: IO stream of C + +

1: Input and output of C language and C++ IO stream

In C language, there are three groups of input and output functions that we often use

Input / outputOperation object
printf/scanfConsole
fprintf/fscanffile
sprintf/sscanfCharacter array (buffer)

The corresponding operations in C + + are as follows

Input / outputOperation object
ostream/isreamConsole
ofstream/istreamfile
ostringstream/istringstreamCharacter array (buffer)

(1) What is flow

Flow refers to the process of material flowing from one place to another. It is an abstract description of an orderly, continuous and directional data. C + + flow refers to the process of information input from external input devices (such as keyboard) to computer internal (memory) and output from memory to external devices (such as screen)
In order to realize this flow, C + + defines the I/O standard class library, and each class is called a flow to complete some functions.

(2) C++ I/O flow

C + + implements a huge class library, in which IOS is the base class, and other classes are directly or indirectly derived from IOS classes
The cin and cout we use when entering the city are objects of this class

A: C + + standard IO stream

**The C + + standard library provides four global flow objects: cin, cout, cerr and cblog. Corresponding to standard input, standard output, standard error and standard log respectively**
For cin, pay special attention to the following points

  1. Space and carriage return can be used as separators between data, so multiple data can be entered in one line or in separate lines. However, if it is a character type and a string, the space cannot be input with cin, and there can be no space in the string, but getline(cin,"this is a test") can be used
  2. When doing algorithm problems, if you use ACM mode, you will often be asked to write the input function by yourself, so`
//Single element input
while(cin>>a)
{	
	//code snippet
}

//Multiple element cyclic input
while(cin>>a>>b>>c)
{
	//code snippet
}
//Accepted by the whole bank
while(cin>>str)
{
	//code snippet
}

B: C + + file IO stream

C/C + + is divided into binary file and text file according to the data format of file content

Reading and writing files in C language is actually a relatively cumbersome operation, because there are many parameters to remember, and you have to open and close files. But in C + +, we still use the idea of object-oriented.
We will mainly use two file streams:

  • ifstream ifile (input only)
  • ofstream ofile (output only)

After instantiating the object, the file operation becomes the operation of calling the interface of these objects.

As follows, we use the ip and port number information of a server for demonstration, which is encapsulated in a structure SeverInfo

struct ServerInfo
{
	char _ip[32];//Ip address
	int _port;//Port number
};

We create a class ConfigManager. The work of this class is to write data to files or read files from memory

The first is the members of the class. The members in the class define a string. This string stores the file name to write data to the disk at that time. Here I define it as myconfig txt

class ConfigManager
{
public:
	ConfigManager(const char* configfile = "myconfig.txt")//structure
		:_configfile(configfile)
	{}

private:
	string _configfile;//Profile name
};

The first step is to open the file and write the contents of the structure in binary mode. The stream to be used is ofstream, and its constructor is

explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
  • The first parameter is the configuration file name, and the second parameter needs to be written in binary mode

The parameters of the write method of the ofstream object are

ostream& write (const char* s, streamsize n);
  • The first parameter is the actual address. Since it is written in binary mode, we strongly convert it to char*

The next step is to open the read in in binary mode. The streams to be used are ifstream and read methods

So binary reading and writing are as follows

	void WriteBin(const ServerInfo& info)
	{
		ofstream ofs(_configfile);//Binary write object
		ofs.write((const char*)& info, sizeof(ServerInfo));//write in
	}
	void ReadBin(const ServerInfo& info)
	{
		ifstream ifs(_configfile);//The secondary system reads from a file
		ifs.read((char*)& info, sizeof(ServerInfo));//Read in
	}

int main()
{
	ConfigManager conf;

	ServerInfo W_info;
	ServerInfo R_info;

	strcpy(W_info._ip, "198.168.0.1");
	W_info._port = 22;

	conf.WriteBin(W_info);//Binary write to disk
	conf.ReadBin(R_info);//Then read the R_info
	cout << R_info._ip << endl;
	cout << R_info._port << endl;


}

Then, for text reading and writing, it is very simple in C + +, because ofstream and ifstream overload the < < and > > operators respectively

	void WriteText(const ServerInfo& info)//Text writing
	{
		ofstream ofs(_configfile);
		ofs << info._ip << endl;
		ofs << info._port << endl;//Pay attention to adding line breaks, or you won't be able to distinguish clearly
	}
	
	void ReadText(ServerInfo& info)
	{
		ifstream ifs(_configfile);
		ifs >> info._ip;
		ifs >> info._port;
	}

int main()
{
	ConfigManager conf;

	ServerInfo W_info;
	ServerInfo R_info;

	strcpy(W_info._ip, "198.168.0.1");
	W_info._port = 22;

	conf.WriteText(W_info);
	conf.ReadText(R_info);
	cout << R_info._ip << endl;
	cout << R_info._port << endl;


}

2: stringstream

(1) Basic introduction

Three classes are defined, namely istringstream,ostringstream and stringstream. The most important one is stringstream

(2) Quote

A: Data type conversion

#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
 
using namespace std;
 
int main()
{
    stringstream sstream;
    string strResult;
    int nValue = 1000;
 
    // Put a value of type int into the input stream
    sstream << nValue;
    // Extract the previously inserted int type value from s sstream and assign it to string type
    sstream >> strResult;
 
    cout << "[cout]strResult is: " << strResult << endl;
    printf("[printf]strResult is: %s\n", strResult.c_str());
 
    return 0;
}

  • The. str() method converts the stringstream type to string

B: String splicing

#include <string>
#include <sstream>
#include <iostream>
 
using namespace std;
 
int main()
{
    stringstream sstream;
 
    // Put multiple strings into ssstream
    sstream << "first" << " " << "string,";
    sstream << " second string";
    cout << "strResult is: " << sstream.str() << endl;
 
    // Empty ssstream
    sstream.str("");
    sstream << "third string";
    cout << "After clear, strResult is: " << sstream.str() << endl;
 
    return 0;
}

  • As mentioned above, multiple strings can be put into stringstream to achieve the purpose of splicing
  • The difference between str ("") and clear (): clear () does not empty the contents. It just clears the initial string conversion type and other operations, which is equivalent to "initialization". If it is converted to int, you can't add content to the original string. At this time, you can use clear(), str() to just change the content to "", and there is no way to add content to it. If it is followed by clear(), you can add content

Keywords: C++ string io

Added by spramod on Sun, 20 Feb 2022 19:37:03 +0200