We have been using C ++ input and output for various exercises since the beginning. input and output are provided by the iostream library. Therefore, it is necessary to discuss this standard library, it is different from the stdio library of C language. From the very beginning, it uses multi-inheritance and virtual inheritance to implement an object-oriented hierarchy. It is provided to programmers as a standard library component of C ++.
Iostream provides input and output support for built-in type objects and file input and output. The class designer can expand the iostream library, to support custom input/output operations.
Why is expansion required to provide support? Here is an example.
# Include <stdio. h>
# Include <iostream>
Using namespace STD;
Class Test
{
Public:
Test (int A = 0, int B = 0)
{
Test: A =;
Test: B = B;
}
Int;
Int B;
};
Int main ()
{
Test T (100,50 );
Printf ("% ??? ", T); // The output format is not clear.
Scanf ("% ??? ", T); // ambiguous input format
Cout <t <Endl; // not clear enough
Cin> T; // not clear enough
System ("pause ");
}
In the code above, whether you use C-style input and output, or the input and output of C ++ are not explicit, because the C language does not have an operator overload mechanism, the stdio library cannot be extended. Therefore, printf () and scanf () cannot support extended recognition of custom class objects, c ++ can use the operator overload mechanism to expand the iostream library so that the system can identify custom types, so that the input and output can clearly know what they are doing and what the format is.
In the preceding example, printf and cout are used to compare the differences between C and C ++ in processing input and output, from the input and output of C far away, we can see that it is a function call method, while C ++ is an object mode,Cout and CIN are ostream and istream objects..
The iostream library in C ++ mainly contains the following header files:
The input and output operations we are familiar with are provided by the istream (input stream) and ostream (output stream) classes. To allow two-way input/output, the iostream class is derived from istream and ostream.
For the inheritance relationships of classes, see:
The iostream library defines the following three standard stream objects:
1. Cin, which indicates the istream Class Object of standard input. Cin allows us to read data such as data from devices.
2. cout, which indicates the ostream Class Object of standard output. Cout allows us to output or write data to the device.
3. cerr, which indicates the osttream Class Object of the standard error. Cerr is the place where program error messages are exported. It can only write data to screen devices.
The output is mainly completed by the overloaded left shift operator (<), and the input is mainly completed by the overloaded right shift operator (>.
> A indicates to put data into object.
<A indicates to extract the data stored in object.
These standard stream objects all have the default corresponding devices, as shown in the following table:
The figure indicates that the default input device of the CIN object is the keyboard, and the default output device of the cout object is the display screen.
In principle, how does C ++ use the CIN/cout object and the left-and right-shift operator overload to implement input and output?
The following uses the output as an example to describe itsImplementation Principle:
Cout is an object of the ostream class. because it points to a standard device (display screen), it is defined as a global object in the iostream header file.
Ostream cout (stdout); // The standard device name in C to which it points by default. It is used as a parameter of its constructor.
In the header file of iostream. H, each basic data type of the ostream class has its friends function to overload the Left shift operator.
Ostream & operator <(ostream & temp, int source );
Ostream & operator <(ostream & temp, char * PS );
.... And so on.
An output statement: cout <"www.cndev-lab.com";, actually called is ostream & operator <(ostream & temp, char * PS); this operator reloads the function, because the returned Stream object reference can be used as the left value, so when the program has similar cout <"www.cndev-lab.com" <"China Software Development Laboratory "; when such a statement appears, it can constitute a continuous output.
The iostream library not only supports the input and output of objects, but also the input and output of file streams. Therefore, before you reload the left-shift and right-Shift Operators in detail, we need to first understand the input and output controllers of the file.
The input and output classes related to files are mainly in fstream. h. This header file is defined. In this header file, three classes are defined. These three classes control various input and output operations on the file, they are ifstream, ofstream, and fstream. The fstream class is derived from the iostream class. The Inheritance relationships between them are shown in.
Because the file device is not a standard default device like the display screen and keyboard, it is in fstream. the H header file contains no pre-defined global objects like cout, so we must define an object of this class by ourselves, to output information to a file (that is, writing data to a file) using a file as a device, use the ofstream class.
The default constructor of the ofstream class is:
Ofstream: ofstream (const char * filename, int mode = IOs: Out, int openprot = filebuf: openprot );
Filename: name of the file to be opened
Mode: how to open the file
Prot: Open File Attributes
The following table lists the options of mode and openprot:
Mode Attribute Table
IOS: APP: open a file in append Mode
IOS: ate: After the file is opened, it is located at the end of the file. IOS: app contains this attribute.
IOS: Binary: open a file in binary mode. The default mode is text. For the differences between the two methods, see the previous article.
IOS: In: open the file as input
IOS: Out: open an output file
IOS: trunc: if the file exists, set the file length to 0.
You can use "or" to connect the preceding attributes, for example, IOS: Out | IOs: binary.
Openprot Attribute Table:
0: normal file, open access
1: Read-Only files
2: Implicit File
4: system files
You can use "or" or "+" to connect the above attributes. For example, 3 or 1 | 2 means opening the file with read-only and implicit attributes.
The sample code is as follows:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <fstream>
Using namespace STD;
Int main ()
{
Ofstream myfile ("C: // 1.txt", IOS: Out | IOs: trunc, 0 );
Myfile <"China Software Development Laboratory" <Endl <"url:" <"www.cndev-lab.com ";
Myfile. Close ()
System ("pause ");
}
After using the file, you can use the close member function to close the file.
IOS: The append mode is app. It is a good habit to judge the File status when append mode is used.
Example:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
# Include <fstream>
Using namespace STD;
Int main ()
{
Ofstream myfile ("C: // 1.txt", IOS: app, 0 );
If (! Myfile) // or write it as myfile. Fail ()
{
Cout <"failed to open the file. The target file may be in read-only status! ";
System ("pause ");
Exit (1 );
}
Myfile <"China Software Development Laboratory" <Endl <"url:" <"www.cndev-lab.com" <Endl;
Myfile. Close ();
}
When defining ifstream and ofstream class objects, we can also leave the file unspecified. In the future, you can use the member function open () to explicitly connect a file to a class object.
For example:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
# Include <fstream>
Using namespace STD;
Int main ()
{
Ofstream myfile;
Myfile. Open ("C: // 1.txt", IOS: Out | IOs: app, 0 );
If (! Myfile) // or write it as myfile. Fail ()
{
Cout <"file creation failed. The disk cannot be written or the file is read-only! ";
System ("pause ");
Exit (1 );
}
Myfile <"China Software Development Laboratory" <Endl <"url:" <"www.cndev-lab.com" <Endl;
Myfile. Close ();
}
Next, let's take a look at how to use the ifstream class object to read the data in the file and then output it to the standard device.
The Code is as follows:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;
Int main ()
{
Ifstream myfile;
Myfile. Open ("C: // 1.txt", IOS: In, 0 );
If (! Myfile)
{
Cout <"file read error ";
System ("pause ");
Exit (1 );
}
Char ch;
String content;
While (myfile. Get (CH ))
{
Content + = CH;
Cout. Put (CH); // cout <ch;
}
Myfile. Close ();
Cout <content;
System ("pause ");
}
In the above example, we use the member function get () to read valid characters in the file one by one, and then use the put () member function to output the data in the file to the standard device (screen) One by one through a loop) the get () member function returns a false value when the file is read to the end of the silence, so we can use this feature as the termination condition of the while loop, we also introduced the C ++ string type in the above example. It is saved to the content one by one during loop reading. To use the string type, it must contain the string type. h header file.
After briefly introducing the ofstream class and ifstream class, let's take a look at the fstream class. The fstream class is derived from iostream, And the fstream class object can perform read and write operations on files.
The sample code is as follows:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
# Include <fstream>
Using namespace STD;
Int main ()
{
Fstream myfile;
Myfile. Open ("C: // 1.txt", IOS: Out | IOs: app, 0 );
If (! Myfile)
{
Cout <"file write error. The file attribute may be read-only! "<Endl;
System ("pause ");
Exit (1 );
}
Myfile <"China Software Development Laboratory" <Endl <"url:" <"www.cndev-lab.com" <Endl;
Myfile. Close ();
Myfile. Open ("C: // 1.txt", IOS: In, 0 );
If (! Myfile)
{
Cout <"file reading error, the file may be lost! "<Endl;
System ("pause ");
Exit (1 );
}
Char ch;
While (myfile. Get (CH ))
{
Cout. Put (CH );
}
Myfile. Close ();
System ("pause ");
}
Because the fstream class can read and write files at the same time, you must explicitly specify the mode and openprot parameters when starting the object.
Next, let's take a look at the basic knowledge of streaming.Stream type?
A simple understanding is the ability to control the input and output classes of string type objects. c ++ not only supports C ++-style string stream control, but also supports C-style string stream control.
Let's take a look at how C ++ controls the C-style string stream. The string in C is actually a character array, data in the character array is arranged consecutively in the memory. We usually use the char STR [size] or char * STR statement to create a C-style character array, to enable the character array as a device and provide input and output operations, C ++ introduces three classes: ostrstream, istrstream, and strstream. To use these classes to create objects, strstream must be included. h header file.
The istrstream class is used to perform input operations on a C-style stream. It uses a string array as the input device.
The ostrstream class is used to perform the output operations of a C-style stream, that is, an array of strings as the output device.
The strstream class also supports the input and output operations of C-style streaming.
The istrstream class is derived from istream (input stream class) and strstreambase (string stream base class). ostrstream is derived from ostream (output stream class) and strstreambase (string stream base class, strstream is derived from iostream (input and output stream class) and strstreambase (string stream base class.
Shows their inheritance relationships:
Streaming is also not a standard device and does not have pre-defined global objects. Therefore, you cannot directly operate on streaming. You need to create objects using constructors.
The constrfunction of istrstream class is as follows:
Istrstream: istrstream (const char * STR, int size );
Parameter 1 indicates the string array, and parameter 2 indicates the array size. When the size is 0, it indicates that the istrstream class object is directly connected to the memory space pointed by STR and ends with/0.
The following sample code uses the istrstream class to create a class object. It sets the stream input device as a string array and uses it to input data to a class object.
The Code is as follows:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
# Include <strstream>
Using namespace STD;
Int main ()
{
Char * name = "www.cndev-lab.com ";
Int arraysize = strlen (name) + 1;
Istrstream is (name, arraysize );
Char temp;
Is> temp;
Cout <temp;
System ("pause ");
}
Ostrstream class is used to execute streaming output. Its constructor is as follows:
Ostrstream: ostrstream (char * _ PTR, int streamsize, int mode = IOs: Out );
The first parameter indicates the character array, the second parameter indicates the size of the array, and the third parameter indicates the open mode.
Here is an example code:
# Include <iostream>
# Include <strstream>
Using namespace STD;
Int main ()
{
Int arraysize = 1;
Char * pbuffer = new char [arraysize];
Ostrstream ostr (pbuffer, arraysize, IOS: Out );
Ostr <arraysize <ends; // when outputting data to a stream object using ostrstream, use ends to end the string.
Cout <pbuffer;
Delete [] pbuffer;
System ("pause ");
}
In the code above, we create a C-style streaming output object ostr, we successfully output data in arraysize to the heap space of the pbuffer pointer pointed to by the ostr object in the form of a string. pbuffer is also the string array to be output.EndsEnd string. If you do not do this, there is a risk of overflow.