C + + Learning 44 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. One is the method of using the controls that we have already described (see: C + + input cout and output cin), and the 2nd type is to use the relevant member functions of the Stream object. Separately described below.

Control the output format using the control character

[Example 13.2] control the output format with a control character.

#include <iostream>#include<iomanip>//don't forget to include this header fileusing namespacestd;intMain () {intA; cout<<"input A:"; CIN>>A; cout<<"Dec:"<<dec<<a<<endl;//output integers in decimal formcout<<"Hex:"<//output integer A in 16 binary formcout<<"Oct:"<<setbase (8) <<a<<endl;//output integer A in eight binary form   Char*pt=" China";//pt points to the string "China"COUT&LT;&LT;SETW (Ten) <<pt<<endl;//Specify the field width as the output stringCout<<setfill ('*') &LT;&LT;SETW (Ten) <<pt<<endl;//Specify the field width, output string, white space ' * ' padding   DoublePi=22.0/7.0;//Calculate PI Values//output as exponential, 8 decimal placesCout<<setiosflags (ios::scientific) <<setprecision (8); cout<<"pi="<<pi<<endl;//Output PI valuecout<<"pi="<<setprecision (4) <<pi<<endl;//Change to decimal placecout<<"pi="<<setiosflags (iOS::fixed) <<pi<<endl;//change to decimal form output   return 0;}
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 commonly used member functions for controlling output formats are shown in table 13.4.

Table 13.4 Flow member functions for output format control

Stream member functions control with the same function function
Precision (N) Setprecision (N) Set the precision of a real number to n bits
Width (n) SETW (N) Set field width to n bits
Fill (c) Setfill (c) Set the fill-in character C
SETF () Setiosflags () Set the output format state, in parentheses should give the format state, the content is the same as the control setiosflags in parentheses, as shown in table 13.5
UNSETF () Resetioflags () Terminates the output format state that has been set, and the contents should be specified in parentheses

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.

Table 13.5 Formatting flags for formatting states

ios::right When you export letters in hexadecimal
format flag effect
ios::left output data aligned to the left in wide range
output data is aligned to the right in the wide range of the field
ios::internal The sign bit of the numeric value is left-aligned within the width of the field, the value is right-aligned, and the middle is filled with padding characters
iOS::d EC Set the radix of integers
ios::oct Set the cardinality of the integer to 8
Ios::hex Sets the cardinality of the integer to 0x
ios::showbase Force the cardinality of the output integer (octal number starts with 0 and the hexadecimal number starts with)
ios::showpoint force output of Dot and mantissa of floating-point number 0
ios::uppercase in scientific notation format E
ios::showpos display "+" for positive numbers
ios::scientific floating-point numbers are formatted in scientific notation
ios::fixed floating-point numbers output in fixed-point format (decimal)
ios::unitbuf refreshes all streams after each output
Ios::stdio clear after each output stdout, stderr

[Example 13.3] output data with the Flow control member function.

#include <iostream>using namespacestd;intMain () {intA= +COUT.SETF (ios::showbase);//Show cardinality symbol (0x or)cout<<"Dec:"<<a<<endl;//default output A in decimal formCOUT.UNSETF (iOS::d EC);//to terminate the decimal format settingCOUT.SETF (Ios::hex);//set the status to hexadecimal outputcout<<"Hex:"<<a<<endl;//output A in 16 binary formCOUT.UNSETF (Ios::hex);//terminates the hexadecimal format settingCOUT.SETF (IOS::OCT);//set the status to output in octalcout<<"Oct:"<<a<<endl;//output A in eight binary formCout.unseft (IOS::OCT); Char*pt=" China";//pt points to the string "China"Cout.width (Ten);//Specify a field width ofcout<<pt<<endl;//Output StringCout.width (Ten);//Specify a field width ofCout.fill ('*');//Specify white space to fill with ' * 'cout<<pt<<endl;//Output String   DoublePi=22.0/7.0;//Output PI valueCOUT.SETF (ios::scientific);//Specify the output in scientific notationcout<<"pi=";//output "pi="Cout.width ( -);//Specify a field width ofcout<<pi<<endl;//Output PI valueCOUT.UNSETF (ios::scientific);//termination of scientific notation StateCOUT.SETF (iOS::fixed);//specify output in fixed-point formCout.width ( A);//Specify a field width ofCOUT.SETF (Ios::showpos);//positive Output "+" numberCOUT.SETF (iOS::Internal);//the number symbol appears on the left sideCout.precision (6);//Keep decimal Placescout<<pi<<endl;//output Pi, note the position of the number "+"   return 0;}

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>) 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.

C + + Learning 44 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.