C ++ formatted output, C ++ output format control, and output format

Source: Internet
Author: User
Tags setf

C ++ formatted output, C ++ output format control, and output format
When outputting data, for the sake of simplicity, the system usually does not specify the output format. The system uses the default format based on the data type, but sometimes you want to output data in the specified format, for example, an integer must be output in hexadecimal or octal format, and only two decimal places must be reserved for the output decimal places. There are two ways to achieve this.
1) method of using a controller;

2) use the member functions of the stream object. The descriptions are as follows.

How to use a controller

# Include <iostream> # include <cstdio> # include <iomanip> using namespace std; int main () {int a; cout <"input :"; cin> a; cout <"dec:" <dec <a <endl; // output the integer cout in decimal format <"hex: "The running result is as follows:

Input a: 34 (value of input)
Dec: 34 (in decimal format)
Hex: 22 (hexadecimal format)
Oct: 42 (octal form)
China (region width is)
* ***** China (the domain width is, and the blank space is filled)
Pi = 3.14285714e + 00 (exponential output, 8 decimal places)
Pi = 3.1429e + 00 (exponential output, 4 decimal places)
Pi = 3.143 (output in decimal form, accuracy is still)

There are some special requirements for input and output, such as specifying the field width when outputting a real number, retaining only two decimal places, and aligning the data to the left or right. C ++ provides the control operators used in the input and output streams (manipulator in some books)


For example, number of outputs with Double Precision:
Double a = 123.456789012345; // assigns an initial value to

1) cout <a; output: 123.456
2) cout <setprecision (9) <a; output: 123.456789
3) cout <setprecision (6); restore the default format (precision is 6)
4) cout <setiosflags (ios plugin fixed); output: 123.456789
5) cout <setiosflags (ios plugin fixed) <setprecision (8) <a; output: 123.45678901
6) cout <setiosflags (ios audio scientific) <a; output: 1.234568e + 02
7) cout <setiosflags (ios audio scientific) <setprecision (4) <a; output: 1.2346e02

The following is an example of integer output:
Int B = 123456; // returns the initial value of B.
1) cout <B; output: 123456
2) cout 3) cout <setiosflags (ios container uppercase) <B; output: 1E240
4) cout <setw (10) <B <',' <B; output: 123456,123456
5) cout <setfill ('*') <setw (10) <B; output: *** 123456
6) cout <setiosflags (ios container showpos) <B; output: + 123456

If the same setw (n) is used in multiple cout statements and setiosflags (ios: right) is used, the right alignment of each row of data can be achieved. If the same precision is specified, the upper and lower decimal points can be aligned.

For example, each row is aligned with the decimal point.

int main( ){double a=123.456,b=3.14159,c=-3214.67;cout<<setiosflags(ios::fixed)<<setiosflags(ios::right)<<setprecision(2);cout<<setw(10)<<a<<endl;cout<<setw(10)<<b<<endl;cout<<setw(10)<<c<<endl;system("pause");return 0;}
The output is as follows:
123.46 (the width of the field is 10, right-aligned, with two decimal places)
3.14
-3214.67
First, set the fixed-point output, take two decimal places, right alignment. These settings are valid for the subsequent output (unless reset), and setw is only valid for the next output, so it must be in the output of a, B, setw (10) must be written before c ).

Use the member functions of the stream object to control the output format
In addition to using the control operator to control the output format, you can also control the output format by calling the member functions used to control the output format in the stream object cout. Common member functions used to control the output format are as follows:

The parameters in the stream member functions setf and the control character setiosflags indicate the format status, which is specified by the format flag. The format flag is defined as an enumeration value in ios. Therefore, when referencing these format tags, you must add the class name ios and the domain operator ":" in front. The format mark is shown in Table 13.5.


For example, use a stream control member function to output data.

Int main () {int a = 21; cout. setf (ios: showbase); // display the base symbol (0x or) cout <"dec:" <a <endl; // The output is in decimal format by default. unsetf (ios: dec); // terminate the cout in decimal format. setf (ios: hex); // set the status cout output in hexadecimal format <"hex:" <a <endl; // output acout in hexadecimal format. unsetf (ios: hex); // terminate the hexadecimal format setting cout. setf (ios: oct); // set the cout output status in octal mode <"oct:" <a <endl; // output the cout in octal mode. unsetf (ios: oct); char * pt = "China"; // pt points to the string "China" cout. width (10); // specify the field width as cout <pt <endl; // output string cout. width (10); // specify the field width as cout. fill ('*'); // fill the cout with '*' in the specified blank space <pt <endl; // output string double pi = 22.0/7.0; // output pi value cout. setf (ios: scientific); // specify to use scientific notation to output cout <"pi ="; // output "pi =" cout. width (14); // specify the field width as cout <pi <endl; // output the pi value cout. unsetf (ios: scientific); // terminate the cout state in scientific notation. setf (ios: fixed); // specify to output cout in the form of a specified point. width (12); // specify the field width as cout. setf (ios: showpos); // a positive number outputs the "+" cout. setf (ios: internal); // The number of characters appears in the left-side cout. precision (6); // reserved decimal cout <pi <endl; // output pi. Pay attention to the "+" Position system ("pause "); return 0 ;}
The running status is as follows:
Dec: 21 (in decimal format)
Hex: 0x15 (hexadecimal format, starting with x)
Oct: 025 (octal format, starting)
China (region width is)
* ***** China (the domain width is, and the blank space is filled)
Pi = ** 3.142857e + 00 (exponential output, domain width, decimal places by default)
+ *** 3.142857 (output in decimal form, accuracy: "+" in the leftmost output ")

Description of the program:
1) The member function width (n) and the control character setw (n) are valid only for the first output item. For example:
Cout. width (6 );
Cout <20 <3.14 <endl;
The output result is 203.14.
When the first output item is 20, the field width is 6, so there are four spaces before 20. When the output is 3.14, width (6) does not work, in this case, output is based on the system's default domain width (output based on the actual data length ). If you want to output data according to the specified width n of the same field, you must call width (n> once before each output item, this is what we did in the above program.
2) In Table 13.5, the output format states are divided into five groups, each of which can only be selected (for example, only one of dec, hex, and oct can be selected, they are mutually exclusive ). After setf and setiosflags are used to set the output format status, if you want to change it to another state in the same group, you should call the member function unsetf (corresponding to the member function self) or resetiosflags (corresponding to the control character setiosflags), first terminate the original state. Then set other statuses. You can see this in this program. Although the program didn't use the member function self and the control operator setiosflags to set the status in dec output format at the beginning, the system is set to dec by default, so it should be changed to hex or oct, you should also use the unsetf function to terminate the original settings. If you delete rows 7th and 10th in the program, although the hex and oct formats are set with the member function setf in rows 8th and 11th, since the dec format is not terminated, because the hex and oct settings do not work, the system still outputs in decimal format.
Similarly, the call to the unsetf function of the program's last 8th rows is also indispensable.
3) when the setf function is used to set the format status, it can contain two or more format flags, which are defined as enumeration values in the ios class, each format flag is represented by a binary character. Therefore, you can use a bitwise OR operator "|" to combine multiple format marks. For example, the last 5th and 6th rows can be replaced by the following line:
Cout. setf (ios: internal I ios: showpos); // contains two status signs, combined with "|"
4) you can see that the control of the output format can be used either the control operator (for example, 13.2) or the related member functions of the cout stream (for example, 13.3 ), the two functions are the same. The control operator is defined in the iomanip header file. Therefore, when using the control operator, the iomanip header file must be included. The member functions of the cout stream are defined in the header file iostream. Therefore, you only need to include the header file iostream and do not need to include iomanip. Many programmers feel that it is convenient and simple to use controllers. Multiple controllers can be used continuously in a cout output statement.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.