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

Source: Internet
Author: User
Tags terminates setf

When outputting data, for simplicity, the format of the output is often not specified, and the system takes the default format based on the type of data, but sometimes you want the data to be output in a specified format, such as requiring that an integer be output in 16 or octal, and only two decimal places are reserved for the small number of the output. There are two ways to achieve this.
1) The method of using the control character;

2) Use the relevant member functions of the Stream object. Separately described below.

How to use a control character

#include <iostream> #include <cstdio> #include <iomanip>using namespace Std;int main () {int A;cout < < "input A:"; Cin >> a;cout << "Dec:" << Dec << a << Endl; output integers in decimal form cout << "hex:" << hex << a << Endl; Output integers in 16 binary acout << Oct: << setbase (8) << a << Endl; Outputs integers in eight binary form achar *pt = "China"; PT points to the string "China" cout << SETW (Ten) << pt << Endl; Specify a field width of, output string cout << setfill (' * ') << SETW (Ten) << pt << Endl; Specify the field width, output string, blank to ' * ' Fill double pi = 22.0/7.0; Calculates pi values//output in exponential form, 8 decimal cout << setiosflags (ios::scientific) << setprecision (8); cout << "pi=" << Pi << Endl; Output pi value cout << "pi=" << setprecision (4) << pi << Endl; Change to decimal cout << "pi=" << setiosflags (ios::fixed) << pi << Endl; Output system ("pause") in decimal form; return 0;}
The results of the operation are as follows:
Input a:34 (Enter the value of a)
dec:34 (decimal form)
HEX:22 (16 in binary form)
Oct:42 (in octal form)
China (field width is)
China (field width is, blank is filled with ' * ')
pi=3.14285714e+00 (exponential output, 8 decimal places)
pi=3.1429e+00 (exponential output, 4 decimal places)
pi=3.143 (fractional output, precision still)

People have special requirements for input and output, such as specify the field width when outputting real numbers, keep only two decimal places, align data to the left or right, and so on. C + + provides the control that is used in the input and output stream (in some books it is called a manipulator)


For example, the output double precision number:
Double a=123.456789012345; Assign an initial value to a

1) cout<<a; Output: 123.456
2) cout<<setprecision (9) <<a; Output: 123.456789
3) cout<<setprecision (6); Restore the default format (6 accuracy)
4) cout<< setiosflags (ios∷fixed); Output: 123.456789
5) Cout<<setiosflags (ios∷fixed) <<setprecision (8) <<a; Output: 123.45678901
6) Cout<<setiosflags (ios∷scientific) <<a; Output: 1.234568e+02
7) cout<<setiosflags (ios∷scientific) <<setprecision (4) <<a; Output: 1.2346E02

The following is an example of an integer output:
int b=123456; Initial value of B assignment
1) cout<<b; Output: 123456
2) cout<3) cout<<setiosflags (ios∷uppercase) <<b; Output: 1E240
4) COUT<<SETW (Ten) <<b<< ', ' <<b; Output: 123456,123456
5) Cout<<setfill (' * ') <<SETW (Ten) <<b; Output: * * * 123456
6) Cout<<setiosflags (Ios∷showpos) <<b; Output: +123456

If you use the same SETW (n) in multiple cout statements and use Setiosflags (ios::right), you can achieve right alignment of each row of data, and if you specify the same precision, you can align the upper and lower decimal points.

For example, each line is aligned with a 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 (Ten) <<A<<ENDL;COUT<<SETW (Ten) <<b<< ENDL;COUT<<SETW (<<c<<endl;system) ("pause"); return 0;}
The output is as follows:
123.46 (field width 10, right-aligned, two decimal places)
3.14
-3214.67
First, set the fixed-point form output, take two decimal places, right-aligned. These settings are valid for subsequent outputs (unless reset), and SETW is only valid for subsequent output entries, so SETW (10) must be written before the output a,b,c.

Control the output format with the member function of the stream object
In addition to controlling the output format with a control, you can control the output format by calling member functions in the Stream object cout that control the output format. The common member functions used to control the output format are as follows:

The flow member function SETF and the parameters in the control setiosflags parentheses represent the format state, which is specified by the format flag. The format flag is defined as an enumeration value in class iOS. Therefore, when referencing these format flags, precede the class name iOS and the domain operator "::". The format flags are shown in table 13.5.


Example: Use flow control member function to output data.

int main () {int a = 21;COUT.SETF (ios::showbase);//display cardinal symbol (0x or) cout << "Dec:" << a << Endl; Default Output ACOUT.UNSETF (iOS::d ec) in decimal form; Terminates the decimal format setting COUT.SETF (Ios::hex); Set the status to hexadecimal output cout << "hex:" << a << Endl; Output ACOUT.UNSETF (Ios::hex) in 16 binary form; Terminates hexadecimal formatting cout.setf (IOS::OCT); Set the status to output in octal cout << "Oct:" << a << Endl; Output ACOUT.UNSETF (ios::oct) in eight binary form, char *pt = "China"; PT points to the string "China" cout.width (10); Specify a field width of cout << pt << Endl; Output string Cout.width (10); Specify a field width of Cout.fill (' * '); Specify white space ' * ' to fill cout << pt << Endl; Output string Double pi = 22.0/7.0; Output pi value cout.setf (ios::scientific); Specify the output of cout << "pi=" by scientific notation; Output "pi=" Cout.width (14); Specify a field width of cout << pi << Endl; Output pi value cout.unsetf (ios::scientific); Termination of scientific notation State COUT.SETF (ios::fixed); Specifies the output cout.width (12) in fixed-point form; Specify a field width of cout.setf (ios::showpos); Positive output "+" number cout.setf (ios::internal); The number symbol appears on the left cout.precision (6); Reserved decimal places cout << pi << Endl; Output PI, note the position of the number "+" system("pause"); return 0;} 
The operating conditions are as follows:
dec:21 (decimal form)
hex:0x15 (16 binary form, beginning with x)
oct:025 (octal form, with opening)
China (field width is)
China (field width is, blank is filled with ' * ')
pi=**3.142857e+00 (exponential output, domain wide, default decimal)
+***3.142857 (decimal output, precision, leftmost output number "+")

A few notes on the program:
1) The member function width (n) and the control character SETW (n) are only valid for the first output item thereafter. Such as:
cout. Width (6);
cout <<20 <<3.14<<endl;
Output is 203.14
At the first output entry 20 o'clock, the field width is 6, so there are 4 spaces before 20, and width (6) has no effect at output 3.14, which is output by the system's default field width (output by the actual length of the data). If it is required to output data in the same field as the specified width n output, you cannot call width (n) only once, and you must call width (N&GT) before outputting each item, which is done in the program above.
2) in table 13.5, the output format status is divided into 5 groups, each group can only choose one (such as Dec, Hex and Oct only one, they are mutually exclusive). After setting the output format state with the member function SETF and the control setiosflags, if you want to change to another state of the same group, you should call the member function UNSETF (corresponding to the member function self) or resetiosflags (corresponding to the control character Setiosflags) , the state of the original setting is terminated first. Then you can see this in the program by setting other states. Program at the beginning although not with the member function self and the control setiosflags set the DEC output format state, but the system is specified by default Dec, so to change to hex or Oct, you should also first use the UNSETF function to terminate the original settings. If you delete lines 7th and 10th in the program, although the hex and Oct formats are set with the member function setf in line 8th and 11th, the hex and Oct settings do not work because the DEC format is not terminated, and the system still outputs in decimal form.
Similarly, the call to the UNSETF function on line 8th of the program is also indispensable.
3) When you use the SETF function to format the state, you can include two or more format flags, since these formatting flags are defined as enumeration values in the iOS class, each with a binary representation, so you can use the bitwise OR operator "|" Combine multiple format flags. If the 5th and 6th lines can be replaced by the following line:
COUT.SETF (ios::internal I ios::showpos); Contains two status flags, with "|" Combination
4) can be seen: control of the output format can be used either as a control (example 13.2), or with the cout flow of the relevant member functions (such as example 13.3), the role of the two are the same. The control character is defined in the header file Iomanip, so you must include the Iomanip header file when you use the control. The member functions of the cout stream are defined in the header file iostream, so only the header file iostream is included, not iomanip. Many program personnel feel that it is easy to use a control character and can use multiple controls consecutively in a cout output statement.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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

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.