C + + Learning 43 input and output related classes and objects

Source: Internet
Author: User

Input and output are the process of data transfer, and data flows from one place to another as well as flowing water. C + + Visually calls this process a stream. The input and output stream of C + + refers to a sequence of a number of bytes of data that are transmitted sequentially from one object to another. Flow represents the flow of information from the source to the destination. In the input operation, the byte stream flows from the input device (such as keyboard, disk) to memory, and in the output operation, the byte stream flows from memory to the output device (such as screen, printer, disk, etc.). Content in a stream can be ASCII characters, binary forms of data, graphic images, digital audio video, or other forms of information.

In fact, a memory buffer is created in memory for each data stream to hold the data in the stream. When you use the cout and insert operator "<<" to output data to the display, the data is sent to the output buffer in the program until the buffer is full or endl, and all the data in the buffer is sent to the display. At input, data entered from the keyboard is placed first in the buffer of the keyboard, and when the ENTER key is pressed, the data in the keyboard buffer is entered into the input buffer in the program, forming the Cin stream, and extracting the data from the input buffer with the extract operator ">>" to the relevant variable in the program. In summary, the stream corresponds to a memory buffer, or the data in the buffer is a stream.

In C + +, the input-output stream is defined as a class. Classes in the I/O Library of C + + are called stream classes. An object defined with a stream class is called a Stream object.

In fact, cout and CIN are not the statements provided in the C + + language, they are objects of the iostream class, and, without the knowledge of classes and objects, they are referred to as cout statements and CIN statements in the context of not causing misunderstandings. Just as C + + does not provide an assignment statement, only an assignment expression is provided, and a semicolon is added to the C + + statement after the assignment expression, which we are accustomed to call an assignment statement for the sake of convenience. Also, in C language commonly used printf and scanf for output and input, printf and scanf is the C language library functions in the input and output functions, it is also customary to be composed of printf and scanf function statements called printf statements and scanf statements. When using them, they should have an accurate understanding of their original concepts.

Having learned about classes and objects, we should have a deeper understanding of the input and output of C + +.

The C + + compilation system provides a iostream class library for input and output. Iostream This word is made up of 3 parts, namely I-o-stream, which means the input and output stream. The Iostream class library contains many classes for input and output. Commonly seen in table 13.1.


Figure 13.1 Table 13.1 Common stream classes in the I/O class Library
class name function in which header file is declared
Ios Abstract base class iostream
IStream
Ostream
iostream
Base classes for common input streams and other input streams
Base classes for general output streams and other output streams
Base classes for general-purpose input and output streams and other input and output streams
iostream
iostream
iostream
Ifstream
Ofstream
FStream
Input file Stream class
Output file Stream class
Input output file Stream class
FStream
FStream
FStream
Istrstream
Ostrstream
Strstream
Input string Stream class
Output string Stream class
Input output string Stream class

Strstream
Str

Stream
Strstream


iOS is an abstract base class, derived from the IStream class and the Ostream class, and the 1th letter I and O in two class names represents input (inputs) and outputs (output). The IStream class supports input operations, the Ostream class supports output operations, and the Iostream class supports input and output operations. The Iostream class is a class derived from the IStream class and the Ostream class through multiple inheritance. The hierarchy of inheritance is shown in Figure 13.1.

C + + file input and output needs to use the Ifstrcam and Ofstream classes, the two class names of the 1th letter I and O respectively represent the input and output, the 2nd letter F for the document (file). Ifstream supports the input operation of the file, Ofstream supports the output operation to the file. Class Ifstream inherits Class IStream, Class Ofstream inherits Class Ostream, Class FStream inherits class Iostream. See Figure 13.2.



Figure 13.2

There are other classes in the I/O class library, but for the average user, these are enough. If you want to learn more about the content and use of the class library, you can refer to the class Library manual for the C + + system you are using.

Header files related to the Iostream class library

The declaration of a different class in the Iostream class library is placed in a different header file, and the user contains the relevant header file with the # include command in his own program, which is equivalent to declaring the required class in this program. Can change-kind of argument: the header file is the interface between the program and the class library, the interface of the Iostream class library is implemented by different header files respectively. Commonly used to have

    • The iostream contains the basic information needed to manipulate the input and output streams.
    • FStream I/O operations for files that are managed by the user.
    • Strstream is used for string stream I/O.
    • Stdiostream is used to mix the I/O mechanisms for C and C + +, for example, to turn C programs into C + + programs.
    • Iomanip This header file should be included when using formatted I/O.
Stream objects defined in the iostream header file

The classes defined in the iostream header file have Ios,istream,ostream,iostream,istream _withassign, ostream_withassign,iostream_withassign, and so on.

The iostream.h contains the basic information needed to manipulate the input and output streams. Therefore, most C + + programs include iostream.h. In the iostream.h header file, not only the relevant classes are defined, but also 4 stream objects are defined, as shown in table 13.2.

4 stream objects defined in table 13.2 files

Object meaning corresponding Equipment the corresponding class the corresponding standard file in C language
Cin Standard input stream Keyboard Istream_withassign Stdin
cout Standard output stream Screen Ostream_withassign StdOut
Cerr Standard error stream Screen Ostream_withassign StdErr
Clog Standard error stream Screen Ostream_withassign StdErr

The above 4 stream objects are defined in the iostream header file in the following form (for example, cout):
Ostream cout (stdout);
When defining cout as the Ostream Stream class object, the standard output device is stdout as a parameter, so it is associated with a standard output device (display), if
cout <<3;
It will output 3 on the monitor's screen.

Overloading operators in the iostream header file

"<<" and ">>" are originally defined in C + + as the left and right displacement operators, because they are overloaded in the iostream header file so that they can be used as input and output operators for standard type data. Therefore, the iostream must be included in the program with the # include command in the program that uses them.
#include <iostream>

In the IStream and Ostream classes (these two classes are declared in iostream), there is a set of member functions that overload the displacement operator << and >> so that it can be used to enter or output data of various standard data types. For different standard data types to be overloaded separately, such as:
Ostream operator << (IM); Used to insert an int data into the output stream
Ostream operator << (float); Used to insert a float data into the output stream
Ostream operator << (char); Used to insert a char data into the output stream
Ostream operator << (char *); Used to insert a string data into the output stream
such as If you have the following expression in your program:
cout<< "C + +";
is actually equivalent to:
Cout.operator << ("C + +")

The value of "C + +" is its first byte address, which is the character type pointer (char *) type, so choose to call the last operator overload function above, by overloading the function body, inserting the string into the cout stream, and returning the Stream object cout.

The operator ' >> ' is overloaded in the IStream class as an extraction operator for the following standard types: char, signed char, unsigned char, short, unsigned short, int, unsigned Int,lon G, unsigned long, float, double, long double, char *, signed char *, unsigned char *, etc.

The "<<" Overload in the Ostream class is an insert operator, and its applicable type adds a void * type in addition to the standard types above.

If you want to use << and >> for your own declared type of data, you cannot simply resolve it by including the iostream header file, and you must overload << and >> yourself.

How do you understand the function of the operator << and >>? There is a simple and figurative approach: they point to the direction of the data movement, for example
>>a
The arrow direction means to put the data in person A. and
<<a
The arrow direction indicates that the data is taken out of a.

C + + standard output stream detailed

The standard output stream is the data flowing to the standard output device (monitor). The Ostream class defines an output stream object, namely cout, Cerr, clog, as described below.

cout Stream Object

Cont is the abbreviation for console output, which means the output in the console (terminal display). A few introductions have been made to cout (see: Classes and objects related to C + + input and output), and here are a few more highlights.

1) cout is not a predefined keyword for C + +, it is an object of the Ostream stream class, defined in iostream. As the name implies, the flow is a flow of data, and the cout stream is the data flowing to the display. The data in the cout stream is added using the stream insert operator "<<" order. If there is
cout<< "I" << "study C + +" << "very hard.";
In order the string "I", "study C + +", "very hard." Plug into the cout stream, cout sends them to the monitor, and outputs the string I study C + + very the display. The cout stream is the carrier that holds the data, and it is not an operator. What people care about is the content in the cout stream, which is what is being exported to the monitor.

2) When you use "ccmt<<" to output a basic type of data, you do not have to consider what the data is, and the system will determine the type of the data and, depending on its type, choose to invoke the operator overload function that matches it. This process is automatic and the user does not have to intervene. If you use the Prinf function to output different types of data in the C language, you must specify the corresponding output format characters separately, which is cumbersome and error-prone. The I/O mechanism of C + + is obviously convenient and secure for users.

3) The cout stream opens up a buffer in memory to hold the data in the stream, and when a endl is inserted into the cout, regardless of whether the buffer is full, all the data in the stream is immediately output, then a newline character is inserted and the stream is flushed (emptying the buffer). Note If you insert a newline character "\ n" (such as cout<<a<< "\ n"), only the output and line breaks are not flushed, but not the cout stream (but not all compilation systems show this distinction).

4) in iostream, only the input and output of the "<<" and ">>" Operators for standard type data is overloaded, but the input and output of the type data declared by the user is not overloaded. If a user declares a new type and wants to enter and output it with the << and >> operators, the << and >> operators are overloaded by using the method described earlier (see: C + + operator overloading).

Cerr Stream Object

The Cerr stream object is a standard error stream, and the Cerr stream has been specified to be associated with the monitor. The role of Cerr is to output error messages to standard error devices. The Cerr and the cout of the standard output stream are similar in function and usage. But there is a difference: the cout stream is usually transmitted to the display output, but can also be redirected to a disk file, while the information in the Cerr stream can only be output on the monitor. When debugging the program, often do not want to run the program error message is sent to other files, and the need to output on the monitor in time, this should be used Cerr. The information in the Cerr stream is specified by the user as needed.

[Example 13.1] has a one-yuan two-time equation ax2+bx+c=0, the general solution is

However, if a=0, or b2-4ac<0, use this formula to make an error.

The program, from the keyboard input A, B, C values, to seek X1 and X2. If a=0 or b2-4ac<0, output an error message.

#include <iostream>#include<cmath>using namespacestd;intMain () {floatA,b,c,disc; cout<<"Please input a,b,c:"; CIN>>a>>b>>C; if(a==0) Cerr<<"A is equal to zero,error!"<<Endl; //Insert an error message into the Cerr stream, on the screen output   Else      if((disc=b*b-4*A*C) <0) Cerr<<"disc=b*b-4*a*c<0"<<endl;//Insert an error message into the Cerr stream, on the screen output      Else{cout<<"x1="<< (-B+SQRT (disc))/(2*a) <<Endl; cout<<"x2="<< (-B-SQRT (disc))/(2*a) <<Endl; }   return 0;}
Clog Stream Object

The clog stream object is also the standard error stream, which is the abbreviation for the console log. It works the same as Cerr, which displays error messages on the terminal display. Difference: Cerr is not through the buffer, directly to the monitor output information, and clog in the buffer, the buffer is full or when the Endl to the display output.

C + + Learning 43 input and output related classes and objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.