cout Output Control

Source: Internet
Author: User
Tags control characters flush function prototype stdin setf

cout output Format Control

If you want to add a format controller to the output stream, load the header file: #include <iomanip>
There are more iomanip in this:
It's mainly about manipulating operators like cin,cout, such as setfill,setw,setbase,setprecision and so on. It is the I/O flow control header file, just like the formatted output in C. Here are some common control functions:

Dec base 10 equals "%d"

Hex Base 16 is equivalent to "%x"


Oct Base 8 equivalent to "%o"//function Permanent

Sample

Cout<<12<

Setprecision (n) sets the display decimal precision to n bit//function Permanent

Sample

SETF (ios:fixed);

Cout<<setprecision (2) <<2.345<<endl; Ouput 2.34//Note First Use SETF (ios::fixed), otherwise the results of their own test


SETW (n) Set field width to n characters//function temp
The control character means that the output width is n. Such as:
COUT&LT;&LT;SETW (3) &LT;&LT;1&LT;&LT;SETW (3) &LT;&LT;10&LT;&LT;SETW (3) <<100; Output results are
1 10100 (the default is right-aligned) when the output length is greater than 3 o'clock (<<1000), SETW (3) does not work.

Setfill (c) Set padding character to C

Setioflags (ios::fixed) fixed floating point display
Setioflags (ios::scientific) index says

Sample Cout<<setiosflags (ios::fixed) <<setprecision (2) <<2.345<<endl; Output 2.34
Setiosflags (Ios::left) left-aligned
Setiosflags (ios::right) Align Right
Setiosflags (IOS::SKIPWS) ignores leading blanks
Setiosflags (Ios::uppercase) 16 number of uppercase output
Setiosflags (ios::lowercase) 16 lowercase output
Setiosflags (ios::showpoint) force display of decimal points
Setiosflags (ios::showpos) force display symbol

Sample:cout<<setiosflags (ios::uppercase) <
Cout<<setioflags (ios::showpoint) <<x<<endl; if float x=1, output 1.000000 does not use direct outputs 1

Cout<<setiosflags (ios::showpos) <<1<<endl;output +1

Write using standard C + +
#include <iostream>
#include <iomanip>//precision settings must be included in the header file

using namespace Std;

int main ()
{
Double a=3.5;
int b=10;
Method One: The format control of operator function
Cout.precision (2), set precision to 2
Right: Set left-aligned; fixed: controls floating-point output format;
SETW (5): Set Output bit width to 5

COUT&LT;&LT;RIGHT&LT;&LT;FIXED&LT;&LT;SETW (5) <<setfill (' 0 ')
<<setprecision (2) <<a<<endl; Output is 03.50

Method Two: The format control of iOS class member function
Cout.precision (4); Setprecision (4), set precision to 4
cout<<a<<endl; Output is 3.5000

Setfill (' 0 '): Set padding character to ' 0 '
Static_cast<double> (b): The integral type B,
Generates a double-precision floating-point copy to operate without changing its value and type
Cout<<fixed<<setfill (' 0 ') <<setprecision (2)
<<fixed<<static_cast<double> (b) <<endl;//output 10.00
return 0;
}


There are many ways we can write this:
/* An example using padding, width, alignment.
#include <iostream.h>
void Main ()
{
cout<< "The first chapter" <<endl;
cout<< "";
COUT.SETF (Ios::left); Set alignment to left
Cout.width (7); Set width to 7, not enough space to fill
cout<< "1.1";
cout<< "What is C language";
COUT.UNSETF (Ios::left); To cancel the alignment, use the default right method
Cout.fill ('. '); To set the Fill method
Cout.width (30); Set width, only useful for the next line of output
cout<<1<<endl;
cout<< "";
Cout.width (7); Set width
COUT.SETF (Ios::left); Set alignment to left
Cout.fill ("); Set padding, default to Spaces
cout<< "1.11";
cout<< "The history of the C language";
COUT.UNSETF (Ios::left); To cancel the alignment
Cout.fill ('. ');
Cout.width (30);
cout<<58<<endl;
Cout.fill (");
cout<< "chapter II" <<endl;
}
We set the width several times so that our spacing is consistent and the alignment is used so that our data is aligned and looks beautiful. We also used the Fill method. It is also possible to implement the manipulation operator below.
/* An example using padding, width, alignment.
#include <iomanip.h>
void Main ()
{
cout<< "The first chapter" <<endl;
cout<< "";
Cout<<setiosflags (Ios::left) &LT;&LT;SETW (7); Set width to 7,left alignment
cout<< "1.1";
cout<< "What is C language";
Cout<<resetiosflags (Ios::left); To cancel the alignment
Cout<<setfill ('. ')        &LT;&LT;SETW (<<1<<endl;) Width is 30, padding is '. ' Output
Cout<<setfill ("); Restore Fill to space
cout<< "";
COUT&LT;&LT;SETW (7) <<setiosflags (Ios::left); Set width to 7,left alignment
cout<< "1.11";
cout<< "The history of the C language";
Cout<<resetiosflags (Ios::left); To cancel the alignment
Cout<<setfill ('. ')        &LT;&LT;SETW (<<58<<endl;) Width is 30, padding is '. ' Output
Cout<<setfill (') << "chapter II" <<endl;
}
We output the same effect, but in my character, I prefer to use a manipulation operator to format the output. Finally, let's look at the format output of floating-point numbers, as in the following example:
* * about the format of floating-point numbers * *
#include <iostream.h>
void Main ()
{
float f=2.0/3.0,f1=0.000000001,f2=-9.9;
cout<<f<< ' <<f1<< ' <<f2<<endl; Normal output
COUT.SETF (Ios::showpos); Force Plus + before positive number
cout<<f<< ' <<f1<< ' <<f2<<endl;
COUT.UNSETF (Ios::showpos); Remove positive number before Plus +
COUT.SETF (Ios::showpoint); Force display of invalid 0 after decimal point
cout<<f<< ' <<f1<< ' <<f2<<endl;
COUT.UNSETF (Ios::showpoint); Suppresses invalid 0 after the decimal point is displayed
COUT.SETF (ios::scientific); Scientific method of Accounting
cout<<f<< ' <<f1<< ' <<f2<<endl;
COUT.UNSETF (ios::scientific); Elimination of scientific notation
COUT.SETF (ios::fixed); Display by point output
cout<<f<< ' <<f1<< ' <<f2<<endl;
COUT.UNSETF (ios::fixed); Cancel the dot output display
Cout.precision (18); Accuracy is 18, normal is 6
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout.precision (6); Precision restored to 6
}
Similarly, we can do the same thing with manipulating operators:
* * about the format of floating-point numbers * *
#include <iomanip.h>
void Main ()
{
float f=2.0/3.0,f1=0.000000001,f2=-9.9;
cout<<f<< ' <<f1<< ' <<f2<<endl; Normal output
Cout<<setiosflags (Ios::showpos); Force Plus + before positive number
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout<<resetiosflags (Ios::showpos); Remove positive number before Plus +
Cout<<setiosflags (Ios::showpoint); Force display of invalid 0 after decimal point
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout<<resetiosflags (Ios::showpoint); Suppresses invalid 0 after the decimal point is displayed
Cout<<setiosflags (ios::scientific); Scientific method of Accounting
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout<<resetiosflags (ios::scientific); Elimination of scientific notation
Cout<<setiosflags (ios::fixed); Display by point output
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout<<resetiosflags (ios::fixed); Cancel the dot output display
Cout<<setprecision (18); Accuracy is 18, normal is 6
cout<<f<< ' <<f1<< ' <<f2<<endl;
Cout<<setprecision (6); Precision restored to 6
}
In addition to the standard input and output, more input functions are provided in C + + system. This write function is mainly getch (), Getche (),
GetChar
(), Cin.get (), Putch (), Putchar (), Cout.put (), gets (), Cin.getline (), puts (). Other than that
There are also some operations that allow buffers to not affect the proper operation of the program, such as: Cin.putback (), Fflush (stdin), Cout.flush (). We
Do a simple description.
1, Getch () and Getche (), non-buffered input, read a character from the keyboard. Getch () read-in characters are not displayed. There is conio.h support.
2, Cin.get (), GetChar (), buffered input, read a character from the keyboard, and display. GetChar () is supported by Stdio.h, and Cin.get () is supported by Iostream.h.
3, Putch () and Putchar (), non-buffered output, output a character to the display. Putch () is supported by Conio.h, and Putchar () is supported by Stdio.h.
4, Cout.put (), buffered output, output a character to the display. Supported by Iostream.h.
5, gets () and Cin.geline (), buffered input, read a string (including spaces, not including the final carriage return), gets () by Stdio.h Support, Cin.getline () by iostream.h support.
6, puts (), non-buffered output, output a string, supported by Stdio.h.
7, Cin.putback (), send a character back to the input buffer.
8, Fflush (stdin), clear the input buffer operation. Unable to clear the operation brought by Cin.get ().
9, Cout.flush (), clear output buffer.
Here we say a little bit about the input/output buffer, which is a space to reduce the interruption of program access to IO. When a program satisfies a refresh condition, the buffer is cleaned up. The specific conditions are:
1. Input buffer
A, when the program requires input, press the ENTER key.
b, the end of the program is encountered.
C, the next input statement is encountered.
D, the purge buffer operation was encountered
E, buffer overflow
2. Output buffer
A, Output buffer overflow
B, encountering the next input statement
C, use the refresh buffer to force the purge
D, the end of the program.
Buffer operations sometimes result in incorrect input of the program, such as scanf (), which, when entered continuously, assigns a carriage return to the next character variable. We must be careful when we operate.

SETF () function with tags for formatting

All aspects of formatting,
To use a variety of formats, just set the bit to 1, and the SETF function is used to set the member function of the tag, which requires one or two in C + +
The constant values of the bits defined in are used as arguments, and the constant values of these bits are described below.

1, C + + in the iOS class defines a bit of constant values, these values are as follows:
A, Ios::boolalpha to make the Boolean value represented by characters
B, iso::showbase the cardinality of the display system is that 16 carry starting with 0x, 8 to 0,
C, ios::showpoint display the decimal point at the end,
D, Ios::uppercase make the 16 a~f in uppercase, while the 0x and the scientific count of letters e are capitalized,
E, Ios::showpos display the symbol in front of a positive number in decimal +

Note that these constants are defined in the iOS class, so they need to be added with iOS:: Qualifiers

For example: COUT.SETF (ios::showbase);
The SETF function needs to be invoked with an object because it is a member function of the stream class.

2. Use the SETF () function with two parameters: the SETF () function can take only one parameter and two parameters. of the SETF () function with two parameters.
The first parameter is the value of the bit to be set, and the second parameter is the value of the bit to be cleared.

Parameter description as shown in the figure
There is a protected data member in C + +, and each of you controls the
3, the format with the SETF () function needs to use the corresponding UNSETF () function to restore the previous settings, such as SETF (Ios::boolalpha) will make the Boolean value of the word
Characters, such as the use of UNSETF (Ios::boolapha), will make the Boolean value in the form of a number.
The SETF function with two parameters can use the UNSETF function of the 1th parameter 0 to restore its default value, such as UNSETF (0,ios::basefield) or direct use of UNSETF (Ios::basefield), note
It is intended that the first UNSETF function with a parameter of 0 cannot be used in Visual C + +, only the second form.

Format output

When outputting data, the format of the output is often not specified for simplicity. The system takes the default format based on the type of data, but sometimes you want the data to be output in the specified format, such as requiring the following six or octal output of an integer, only two decimal digits for the output, and so on; there are two ways to do this. One is using a control character, and the other is using the relevant member function of the stream object. The following are described separately:

1. Control the output format with the control character







It should be noted that:

These controls are defined in the header file Iomanip, so that the program should include the header file Iomanip. The following examples let you know how to use them.

[Indent] Example 2 control output format with a control character


#include <iostream>
#include <iomanip>//Don't forget to include this header file


using namespace Std;
int main ()
{
int A;
cout<< "input A:";
cin>>a;
cout<< "Dec:" <<dec<<a<<endl; Output integer in the above form
cout<< "Hex:" <cout<< "Oct:" <<setbase (8) <<a<<endl;//output integer A in eight-way
Char *pt= "the";
PT point to String "in"
COUT&LT;&LT;SETW (<<pt<<endl;) Specify a field width of 10, output string
Cout<<setfill (' * ') &LT;&LT;SETW (a) <<pt<<endl;//specifies a field width of 10, an output string, and white space is filled with "*"
Double pi=22.0/7.0; Calculate PI Value
Cout<<setiosflags (ios::scientific) <<setprecision (8);//output in exponential form, 8 decimal digits
cout<< "pi=" <<pi<<endl; Output PI Value
cout<< "pi=" <<setprecision (4) <<pi<<endl;//changed to 4 decimal places
cout<< "pi=" <<setiosflags (ios::fixed) <<pi<<endl;//to decimal form output
return 0; }

The results of the operation are as follows



INPUTA:34 (Enter a value)
dec:34 (decimal form)
HEX:22 (hexadecimal)
oct:42 (octal form)
(Domain width is 10)
(Domain width is 10, blank is ' * ' filled)
pi=3.14285714e+00 (exponential form output, 8 decimal digits)
pi=3.1429e+00) (exponential form of a small, 4-digit decimal)
pi=3.143 (decimal form output, the tip is still 4)


2. Controlling output format with a member function of a Stream object




In addition to controlling the output format with a control character, you can control the output format by calling the member function in the Stream object cout to control the output format. The common member functions used to control the output format are shown in table 4.



The flow member functions SETF and the parameters in the setiosflags brackets denote the format state, which is specified by a format flag. The format flag is defined as an enumeration value in class iOS. So when referencing these format flags, precede with the class name iOS and the domain operator "::". The format signs are shown in table 5.





[/indent] [Indent] Example 3 uses a Flow control member function to output data.


#include <iostream>
using namespace Std;
int main ()

{
int a=21;
COUT.SETF (ios::showbase); Set the cardinality symbol when outputting
cout<< "Dec:" <<a<<endl; Default to output a in decimal form
COUT.UNSETF (iOS::d EC); Terminating decimal format settings
COUT.SETF (Ios::hex); Setting the state in hexadecimal output
cout<< "Hex:" <<a<<endl; Output A in 16 binary form
COUT.UNSETF (Ios::hex); To terminate hexadecimal formatting
COUT.SETF (IOS::OCT); Set the state to octal output
cout<< "Oct:" <<a<<endl; Output A in eight binary form
COUT.UNSETF (IOS::OCT); Terminates the output format setting in eight
Char *pt= "the"; PT point to String "in"
Cout.width (10); Specify a domain width of 10
cout<<pt<<endl; Output string
Cout.width (10); Specify a domain width of 10
Cout.fill (' * '); Specify whitespace to ' * ' Fill
cout<<pt<<endl; Output string
Double pi=22.0/7.0; Calculate PI Value
COUT.SETF (ios::scientific)//specified with scientific notation output
cout<< "pi="; Output "pi="
Cout.width (14); Specify a domain width of 14
cout<<pi<<endl; Output "PI value
COUT.UNSETF (ios::scientific); Termination of the scientific notation State
COUT.SETF (ios::fixed); Specify the output in fixed-point form
Cout.width (12); Specify a domain width of 12
COUT.SETF (Ios::showpos); Display the "+" number when outputting positive numbers
COUT.SETF (ios::internal); The number character appears on the left
Cout.precision (6); Keep 6 decimal digits
cout<<pi<<endl; Output PI, note the position of "+"
return 0;}

The operating conditions are as follows:



dec:21 (decimal form)
HEX:OXL5 (16 in form, beginning with 0x)
oct:025 (octal form, beginning with O)
(Domain width is 10)
(Domain width is 10, blank is ' * ' filled)
pi=**3.142857e+00 (exponential form output, field width 14, default 6 decimal digits)
3.142857 (decimal form transmission ㈩, precision is 6, leftmost output number "+")


Description




1, the member function width (n) and the control character SETW (n) are valid only for the first output item thereafter. If you require that you output data with a width of n output in the same domain as you specify, you cannot call only one width (n) at a time, but you must call width (n) once before outputting each item.


2. The output format status in table 5 is divided into 5 groups, only one of each group can be selected at the same time (for example, Dec,hex and Oct can only choose one, they are mutually exclusive), after the output format state is set with the member function SETF and the control character 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 SETF) or resetiosflags (corresponding to the control character Setiosflags) to terminate the state of the original setting. And then set other states.

Similarly, the call to the UNSETF function in line 8th of the program is indispensable. Readers may wish to try on the machine.


3. When you set the format state with the SETF function, you can include two or more format flags, because these format flags are defined as enumeration values in the iOS class, each format flag is represented by a binary, so you can combine multiple format flags with "bit or" operator "I"


4, you can see: The output format control, either with the control character (example 2), can also use the cout flow of the relevant member functions (such as example 3), the effect is 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 character. The member functions of the cout stream are defined in the header file iostream, so you only need to include the header file iostream, and you do not have to include Iomanip. Many program people feel that using a control character is easy, and you can use a variety of control characters in a cout output statement.


5, on the control of the transmission of the mountain, in the use of some details will be encountered, it is not possible to all involved. When you encounter a problem, please consult a special manual or a test on the machine can be solved.

member functions for an input stream class for a char-type array of characters

Use the member function of the input stream class to enter:
Note: These member functions can only be used for character arrays of type char, not for string objects.


1. Enter a single character using the Get () function: The Get () function that enters a single character is a member function in the class IStream that invokes the object that they need to use the class
To invoke, the function has two prototypes, that is, get (char &ch) and got (void).
A, get (char &ch) function: This function returns a reference to the calling object, note that the parameter type of the function must be of type char, not int
Type variables, such as Cin.get (a) where parameter a can only be a char type, cannot be an int, and an error occurs if the int is the type. This function can even
Continued input, i.e. cin.get (a). get (a);
b, get (void) function: The function returns the value of int, and calls the Get function without using parameters. The function cannot be entered continuously, such as cin.get (). Get ()
Is wrong.
c, two get functions receive a single character entered and do not skip whitespace symbols and carriage return line breaks. If more than 2 characters are entered, the
The word Fu Paocun in the input stream, leaving the next input. For example, there is char A; Cin.get (a);cout<<a; Cin.get (a); cout<<a; If you enter a and press ENTER
, the second get call will no longer prompt for the input character, but instead accepts the carriage return line after the first input of a single character A, the
Enter the last entry only once, and output a and then wrap. Similarly, if you enter two characters in a row, such as AD, the first character A is assigned to the first variable,
The two character D is assigned to the second variable, and there is no indication of a two-time input, which is not the effect we expect. Same get () function
Have the same laugh, that is char A; A=cin.get (); cout<<a; A=cin.get (); cout<<a; If you enter a and press ENTER, there is the same as get (char &ch)
Laughing fruit. Note When you use the >> operator, you will omit symbols such as spaces and carriage return lines, and the Get function will not. The way to solve the problem is
Use the Ignore () function to read and discard the remaining characters before the second input, prompting you to enter two times.


2. Use the Get and Getline functions to enter a string:
A, the string input get and getline function prototypes are as follows: Get (char *, int, char); Get (char*, int); Getline (Char*,int, char); Getline (Char*,int);
Its back type is IStream & that is to say that these functions can be spliced output. The functions of two parameters enter a string of the specified length, and the second
The number of arguments is 1 greater than the number of characters that will be entered, because the last character is the character that ends the string. of a function with three parameters.
The third argument is the demarcation character, which means that when the input encounters a third character, the following characters are not entered, even if the input string is not
reaches the specified length.
The difference between get and getline is that the Get function leaves the delimiter in the input stream so that the next time you enter it, the delimiter is entered. and Getline is
Read and discard this delimiter. such as Cin.get (a,3, ' z ') if you enter Abz, the character z is left in the input stream, waiting for the next input, such as in get
After the function is followed by a cin>>b;, the character Z is assigned to the variable B without prompting for the input again.
C, the number of characters entered exceeds the specified number of lengths: for the Getline function, if the number of characters entered is longer than the specified number of characters
, and the last character is not a delimiter, the Failbit bit is set. For example Cin.getline (a,3, ' z ') if you enter ABDC, the Failbit bit is set, and the
If the input Abzde does not set the Failbit bit, because although the input exceeds the specified length, but the last character is a delimiter Z, it is not set
Place the failbit bit, and leave the character after the demarcation character z in the input stream, leaving the next input. For a Get function, when the number of characters entered exceeds the
The specified length does not set the Failbit bit, and the peek () function can be used to check whether the program is a normal end input for a get function. If you use a get
When a function enters a specified number of characters, more characters are used as the next character, and for the Getline function, the next loss is closed
In, because the Getline function sets the state bit failbit when the number of characters entered exceeds the specified number, and the input is closed before the state bit is cleared,
Unless it is reset. For both functions, the eofbit bit is set when the end of the file is reached, and the Badbit bit is set when the stream is corrupted.
D, when the input is a null character processing: For the Get function, if entered is a null character will set the Failbit bit, but for the Getline function
, the bit is not set. such as Cin.get (a,3), then if the input directly press ENTER, the Get function will be set failbit bit, and for getline
function, the bit is not set.
E, for the above get and getline functions, whether the input is a single character or a string, you need to use the Ignore function to read and discard the redundant
Enter the characters so that the subsequent input program works properly.


3, read () function: The function prototype is iostream& read (const char* addr,streamsize N). The call method is Cin.read (a,144);
The character is placed in the address from a beginning of memory, if you have not read 144 characters to the end of the file, set Ios::failbit. The read function and get
Unlike getline, the Read function does not add the above value character after the input, and that means that the number of inputs does not have to be 1 less than the specified number, which is not
Converts the entered character to a string. The read function can be spliced.


4, Readsome () function: The prototype is iostream& readsome (char* addr,streamsize N). Indicates that n characters are placed in memory starting with the address from addr,
This function is similar to the Read function, except that if n characters are not read, the set file end state bit ios::eofbit.


5. Write () function: The prototype is iostream& write (const char* addr,streamsize n), which means that the N characters starting from the address addr are written to the stream.


6. Peek () function: The Peek function returns the next character in the input stream, but does not extract the characters from the input stream, which means that he makes it possible to view the next loss
into the character.


7, Gcount () function: Returns the number of characters read by the last unformatted extraction method. Non-formatted extraction methods such as Get and Getline functions,>>
This operator is a format extraction method.


8, strlen () function: Calculates the number of characters in an array, which is faster than using the Gcount function to compute the number of characters.


9, note: The above functions are input stream class member functions, use them when you need to use the input stream class object to invoke, such as Cin.get ().


Reminder again: The above function is only suitable for arrays of type char and not for string objects. such as String A; Cin.get (a,3); Then there will be a mistake.
Error, because class string object A cannot be converted to an array of type char.

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.