c++--input, output, and file

Source: Internet
Author: User
Tags flushes function prototype traits

One, C + + input and Output overview

1.1, Stream and buffer

C + + programs treat input and output as byte streams. When entered, the program extracts bytes from the input stream, and when output, the program inserts the bytes into the output stream. For a program of face text, each byte represents a character, and more generally, a byte can form a binary representation of a character or numeric data. The bytes in the input stream may be from the keyboard or from a storage device such as a hard disk or other program. The bytes in the output stream can flow to a screen, printer, storage device, or other program. A stream acts as a bridge between a program and a flow source or flow target. This allows C + + programs to treat input from the keyboard and input from the file in the same way. The C + + program checks only the byte stream without knowing where the bytes came from. Similarly, by using a stream, the C + + program processes the output independently of its whereabouts. Therefore, the management input will contain two steps:

* Associate the stream with the program where the input goes.

* Connect the stream to the file.

In other words, the input stream requires two connections, one per end. The file end connection provides the source of the stream, and the terminal connection dumps the stream's outflow into the program (the file-side connection can be a file, or it can be a device). Similarly, the management of the output involves connecting the output to the program and associating the output target with the stream.

In general, input and output can be processed more efficiently by using buffers. A buffer is a block of memory used as a mediator, which is a temporary storage tool that transfers information from a device to a program or from a program to a device.

1.2. Streams, buffers, and iostream files

Managing flows and buffers is a bit complicated, but iostream (formerly Iostream.h) files contain classes that are specifically designed to implement, manage flows, and buffers. C++98 version c++i/o defines some class templates to support char and wchar_t data; c++11 adds char16_t and char32_t materialization. By using the TypeDef tool, C + + enables these template char materialization to mimic traditional non-template I/O implementations. Here are some of these classes:

The *streambuf class provides memory for buffers and provides class methods for populating buffers, accessing buffer contents, flushing buffers, and managing buffer memory;

The *ios_base class represents the general characteristics of a stream, such as whether it is readable, binary, or text-flow.

The *ios class is based on Ios_base, which contains a pointer member that points to the Streambuf object;

The *ostream class is derived from the iOS class and provides an output method;

The *istream class is also derived from the iOS class and provides an input method;

The *iostream class is based on the IStream and Ostream classes, thus inheriting the input method and the output method.

To use these tools, you must use the appropriate class object. For example, use a Ostream object, such as cout, to process the output. Creating such an object opens a stream, automatically creates a buffer, and associates it with the stream, making it possible to use class member functions.

  Add: Flush define I/O

The Iso/ansi standard c++98 changes the I/O in two ways. The Prime Minister is a change from ostream.h to Ostream, with ostream putting classes in the Std namespace. Second, I/O classes are rewritten. To become an international language, C + + must be able to handle an international character set or a wider character type that requires 16 bits. Therefore, the language adds wchar_t ("wide") character types based on the traditional 8-bit char ("narrow") type, while c++11 adds the type char16_t and char32_t. Each type needs to have its own I/O tool. Instead of developing two separate classes (now 4 sets), the standard Committee developed a set of I/O class templates, including Basic_istream<chart, traits<chart>>, and basic_ostream< CharT, traits<chart>>. The traits<chart> template is a template class that defines specific attributes for character types, such as how to compare characters for equality and the EOF value of characters. The C++11 standard provides the char and wchar_t materialization of I/O. For example, IStream and Ostream are both char-materialized typedef. Similarly, Wistream and Wostream are the embodiment of wchar_t. For example, the Wcout object is used to output a wide character stream. These definitions are included in the header file ostream.

Some type-independent information in the iOS base class is moved to the new Ios_base class, which includes various formatting constants, such as Ios::fixed (now ios_base::fixed). In addition, Ios_base contains some options that are not included in older iOS.

The C + + iostream class Library manages a lot of detail. For example, including a iostream file in your program will automatically create 8 stream objects (4 for narrow character streams and 4 for wide character streams).

The *cin object corresponds to the standard input stream. By default, this stream is associated to a standard input device (usually the keyboard). The Wcin object is similar to this, but the wchar_t type is processed.

The *cout object corresponds to the standard output stream. By default, this stream is associated to a standard output device (usually a monitor). The Wcout object is similar to this, but the thing that is handled is wchar_t type.

The *cerr object corresponds to a standard error stream and can be used to display error messages. By default, this stream is associated to a standard output device (usually a monitor). This stream is not buffered, which means that the information will be sent directly to the screen without waiting for the buffer to fill up or new newline characters. The Wcerr object is similar to this, but the wchar_t type is processed.

The *clog object also corresponds to the standard error stream. By default, this stream is associated to a standard output device (usually a monitor). This stream is buffered. The Wclog object is similar to this, but the wchar_t type is processed

* object represents the flow-what does that mean? When a iostream file declares a cout object for a program, the object contains data members that store information about the output, such as the width of the field used to display the data, the number of decimal digits, the Count method used to display the integer, and the address of the Streambuf object that describes the buffer used to process the output stream. The following statement passes the string "Hello world!" by pointing to the Streambuf object Put the characters in the cout managed buffer: cout << "Hello world!";

In short, the end of the stream is connected to the program, and the other end is connected to the standard output, and the Cout object with the help of the Streambuf object, a stream of bytes in the manager.

1.3. redirect

The standard input and output flow is often connected to the keyboard and screen. However, many operating systems, including Unix,linux and windows, support redirection, which enables the ability to change standard input and standard output.

Second, using cout for output

C + + sees the output as a byte stream (depending on the platform, it can be 8-bit, 16-bit, or 32-bit bytes, but all bytes), but in the program, much of the data is organized into larger units than bytes. For example, the ING type is represented by a 16-bit or 32-bit binary, and a double value is represented by a binary number of 64 bits. But when you send a stream of bytes to the screen, you want each byte to represent a character value. Therefore, one of the most important tasks of the Ostream class is to convert a numeric type (such as int or float) to a stream of characters in textual form. That is, the Ostream class transforms the internal representation of the data (BITS mode) into an output stream consisting of character bytes (there will be biomimetic grafts in the future, allowing the binary data to be translated directly). To perform these transformation tasks, the Ostream class provides several class methods.

2.1. Overloaded << Operators

In C + +, the default meaning of the,<< operator, like C, is the bitwise left shift operator. The Ostream class, however, redefined the << operator by overloading it with output. In this case,,<< is called the insert operator instead of the left-shift operator. The insert operator is overloaded so that it can recognize all the basic types in C + +:

* unsigned char;

* Signed Char;

* CHAR;

* SHORT;

* unsigned short;

* INT;

* unsigned int;

* LONG;

* unsigned long;

* Long Long (C++11);

* Unsigned long long (c++11);

* FLOAT;

* DOUBLE;

* long double;

For each of these types, the Ostream class provides the definition of the operator<< () function. Therefore, if you use one of the following statements, and value is one of the types listed earlier, the C + + program corresponds to the operator function that has the corresponding feature tag:

cout << value;

2.1.1 Output and pointers

The Ostream class also defines the INSERT operator function for the following pointer type:

* Const signed char *;

* Const unsigned char *;

* const char *;

* void *.

C + + uses a pointer to the location where the string is stored to represent the string. The pointer can be in the form of a char array, an explicit char pointer, or a string that is enclosed in quotation marks, and uses the terminating null character in the string to determine when to stop displaying the character.

For other types of pointers, C + + corresponds to void * and prints the numeric representation of the address. If you want to get the address of a string, you must cast it to a different type, for example:
int num = 12;

char * name = "Tom";

cout << &num; Print the address of the variable num

cout << name;//will print the string "Tom"

cout << (void *) name;//will print the address of the string "Tom"

2.1.2 Splicing Output

The return type of all avatars of the insert operator is Ostream &. In other words, the prototype format is as follows:

Ostream & operator<< (type);

(where type is the type of data to be displayed) the return type Ostream & means that using the operator returns a reference to the Ostream object, and the function definition indicates that the reference is to the object used to invoke the operator. In other words, the return value of an operator function is the object that invokes the operator. This feature allows the output to be connected by inserting.

 2.2 Other methods of Ostream

In addition to various operator<< () functions, the Ostream class provides the put () method and the Write () method, which is used to display characters, which are used to display strings.

Initially, the put () prototype is as follows:

Ostream & Put (char);

The current standard is the same, but is templated to apply to wchar_t. It can be called using the class method notation:

Cout.put (' W ');

Where cout is the object that invokes the method, put () is a member function. Like the << operator function, the function also returns a reference to the calling object, so it can be spliced out with it:

Cout.put (' A). Put (' B ');

If the prototype is appropriate, you can use a numeric parameter (such as int) for put (), and let the function prototype automatically convert the parameter to the correct char value. For example:

Cout.put (65);//Display a

Cout.put (66.3);//display B

The Write () method displays the entire string, with its template prototype as follows:

Basic_ostream<chart, Traits> & Write (const char_type* s, streamsize N);

The first parameter of write () provides the address of the string to display, and the second parameter indicates how many characters to display. When you call write () with cout, Char is called to materialize, so the return type is Ostream &.

1#include <iostream>2 3 intMain ()4 {5     usingstd::cout;6     usingStd::endl;7     Const Char* State1 ="Florida";8     Const Char* State2 ="Kansas";9     Const Char* State3 ="Euphoria";Tenstd::size_t len =Std::strlen (state2); Onecout <<"increasing loop index:\n"; A     inti =0; -      for(i =1; i < Len; i + +) { - Cout.write (State2, i); thecout <<Endl; -     } -      -cout <<"decreasing loop index:\n"; +      for(i = (int) Len; i >0; i--) { -Cout.write (State2, i) <<Endl; +     } Acout <<"exceeding string length:\n"; atCout.write (State2, Len +5) <<Endl; -     return 0; - } -  - Output Result: - increasing loop index: in K - Ka to Kan + Kans - Kansa the decreasing loop index: * Kansas $ KansaPanax Notoginseng Kans - Kan the Ka + K AExceedingstringLength: theKansaseuph

As you can see from the program above, the write () method does not stop printing characters when it encounters an empty character, but only prints a specified number of characters, even if the bounds of the string are exceeded.

The write () method can also be used for numeric data, you can cast the address of a number to char *, and then pass it to it:

#include <iostream>int  main () {    long560031841;    Std::cout.write ((charsizeof(val));         return 0 ;} Output result: AHA!

This does not convert the numeric value to the corresponding character, but rather transmits the bit representation stored in memory. For example, a Long value of 4 bytes will be transferred as 4 separate bytes. The output device interprets each byte as an ASCII code.

2.3 Flush Output Buffers

What happens if the program uses cout to send bytes to standard output? Because the Ostream class buffers the output processed by the Cout object, the output is not immediately sent to the destination address, but is stored in the buffer until the buffer fills up. The program then flushes the (flush) buffer, sends the content out, and empties the buffer to store the new data. Typically, the buffer is 512 bytes or its integer multiples. Buffering can save a lot of time when the standard output is connected to files on the hard disk.

If the implementation cannot flush the output when desired, you can use one of the two controls to force the refresh. The null character flush flushes the buffer, and the control Endl flushes the buffer and inserts a newline character. These two controls are used in the same way as variable names:

cout << "Hello world!" << flush;

cout << "Wait for me." << Endl;

In fact, the control is also a function. For example, flush () can be called directly to flush the cout buffer:

Flush (cout);

However, the Ostream class overloads the << insert operator so that the following expression is replaced with the function call Flush (cout):

cout << Flush;

Therefore, a more convenient insertion notation can be used to successfully refresh.

2.4 Using cout for formatting

The Ostream Insert operator converts the value to text format. By default, the values are formatted in the following way.

* For char values, if it represents a printable character, it is displayed as a character in a field with a width of one character.

* For numeric integers, it is displayed in decimal form in a field that just holds the number and minus sign (if any);

* The string is displayed in a field with a width equal to the length of the string.

The default behavior of floating-point numbers varies. The differences between old-fashioned implementations and modern implementations are explained in detail below.

* Modern: Floating-point type is displayed as 6 bits, the end of 0 is not displayed (note that the number of digits displayed is not related to the precision setting when the number is stored). The number is indicated by a fixed-point representation or scientific notation, depending on its value. Specifically, the scientific notation is used when the exponent is greater than or equal to 6 or less than or equal to 5. In addition, the field width fits exactly the number and minus sign (if any). The default behavior corresponds to the standard C library function fprintf () with the%g specifier.

* Old-fashioned: floating-point types are shown with 6 decimal places and 0 at the end are not displayed (note that the number of digits displayed does not have anything to do with the accuracy of the number being stored). Whether the numbers are displayed in fixed-point notation or in scientific notation depends on his value. In addition, the field width fits exactly the number and minus sign (if any).

Because the display width of each value equals its length, you must explicitly provide a space between the values, otherwise the adjacent values will not be separated.

Note: Not all compilers can produce output that conforms to the current C + + standard format. In addition, the current standard allows for regional changes. For example, a European implementation might follow a European style: use commas instead of periods to represent decimal points. In other words, 2.54 will be written in 2, 54. The Regional library (the header file locale) provides a mechanism for using a specific style-influenced (imbuing) input or output stream, so the same compiler can provide multiple regional options. This chapter uses the American format.

(1) Change the counting system used when displaying

The Ostream class is derived from the iOS class, and the latter is derived from ios_base. The Ios_base class stores information that describes the format state. For example, some bits in a class member determine the counting system used, and the other member determines the field width. By using the control character (manipulator), you can control the technical system used when displaying integers. By using the member function of Ios_base, you can control the field width and number of decimal digits. Because the Ios_base class is an indirect base class for ostream, its methods can be used with Ostream objects (or descendants), such as cout.

Note: Members and methods in the Ios_base class were previously located in iOS. Now, Ios_base is the base class for iOS. In the new system, iOS is a template that contains char and wchar_t materialization, while ios_base contains non-template features.

To control whether integers are displayed in decimal, hexadecimal, or octal, you can use the DEC, hex, and Oct controls. For example, the following function call sets the Cout object's count system format state to 16 binary:

Hex (cout);

When the above settings are complete, the program prints the integer values in 16-in-a format until the formatting state is set to another option. Note that the control is not a member function, so it does not have to be called through an object.

Although the controls are actually functions, they are typically used in the following ways:

cout << Hex;

The Ostream class overloads the << operator, which makes the above usage equivalent to the function call Hex (cout). The control is located in the namespace Std. The following code shows how the control is used (note that you can use the control character alone, or as a series of inserted parts):

#include <iostream>intMain () {using namespacestd; cout<<"Enter a number:"; intN; CIN>>N; STD::stringStr5,' '); cout<<"N"<< Str <<"n*n\n"; cout<< n << str << n*n <<"(decimal) \ n"; //set as hexadecimal systemcout <<Hex; cout<< N <<str; cout<< N*n <<"(hexadecimal) \ n"; //set to octal systemcout << Oct << n << str << n * N <<"(octal) \ n";    Dec (cout); cout<< n << str << n * N <<"(decimal) \ n"; return 0;} Output Result: Enter a number: AN N*N A     144(decimal) C -(hexadecimal) -      -(octal) A     144(decimal)

(2) Adjust field width

  

c++--input, output, and file

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.