Control output format in C + +

Posted by adamp1 on Thu, 03 Feb 2022 11:25:34 +0100

setprecision(n) controls the number of floating-point numbers displayed in the output stream. The default stream output value of C + + is 6 significant bits, so no matter how much data is, only six bits are output. If setprecision(n) is used with setiosflags(ios::fixed) or setiosflags(ios_base::fixed), the number of digits to the right of the decimal point can be controlled. setiosflags(ios::fixed) is a fixed-point representation of real numbers. If used with setiosnags(ios::scientific), you can control the decimal places of the exponential representation. setiosflags(ios::scientific) is a real number expressed exponentially.

Common control characters of I/O flow:

When using the control character, add the file #include < iomanip > at the beginning of the program. C + + has two methods to control the format output: 1. Use the format control character; 2. Use the member function format controller of the stream object:

dec , set the cardinality to 10

hex # set cardinality to 16

oct # set cardinality to 8

setfill(c) sets the fill character C

setprecision(n) sets the display decimal precision to n digits

setw(n) sets the field width to n characters

setiosflags(ios::fixed) fixed floating point display

setiosflags(ios::scientific) index

setiosflags(ios::left) left justified

setiosflags(ios::right) right justified

setiosflags(ios::skipws) ignores leading whitespace

setiosflags(ios::uppercase) hexadecimal number uppercase output

setiosflags(ios::lowercase) hexadecimal lowercase output

Member function:

flags(10) set the cardinality to 10

flags(16) set the cardinality to 16

flags(8) set the cardinality to 8

flags(c) sets the fill character C

precision(n) sets the display decimal precision to n digits

width(n) sets the field width to n characters

In the new version of c + +, the header file has been replaced by iomanip h.

Here are some common functions:

dec set cardinality to 10, equivalent to "% d"

hex set cardinality to 16, equivalent to "% X"

oct set cardinality to 8, equivalent to "% o"

setfill(c) set the fill character to C

Set precision to decimal (n)

setw(n) sets the field width to n characters

setiosflags(ios::fixed) fixed floating point display

setiosflags(ios::scientific) index

setiosflags(ios::left) left justified

setiosflags(ios::right) right justified

setiosflags(ios::skipws) ignore leading whitespace

Setiosflags (IOS:: uppercase) hexadecimal number uppercase output

Setiosflags (IOS:: lowercase) hexadecimal lowercase output

setiosflags(ios::showpoint) forces the display of decimal points

setiosflags(ios::showpos) forces the display of symbols

I have tested some of the above codes myself, but there are too many formats. I'll use them later.

  View Code

 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 int main ()
 5 {
 6     double a=123456.343001;
 7     cout<<"a The value of is 123456.343001"<<endl<<endl; 
 8     cout<<"Without any operation, only 6 six digit data is displayed by default:"<<a<<endl<<endl;
 9     cout<<"Specifies 10 decimal places and is represented by floating-point numbers setiosflags(ios::fixed): "<<setiosflags(ios::fixed)<<setprecision(10)<<a<<endl<<endl;
10     cout<<"Specified as 10 decimal places and expressed in exponential form setiosflags(ios::scientific),Is to leave significant bits: how to specify more significant bits than the original significant bits, and its output is its own number of bits:"<<setiosflags(ios::scientific)<<setprecision(12)<<a<<endl<<endl;
11     cout<<"Specified as 10 decimal places and expressed in exponential form setiosflags(ios::scientific),Is to leave significant bits: setprecision(10)Specify to leave 10 significant bits"<<setiosflags(ios::scientific)<<setprecision(10)<<a<<endl<<endl;
12     cout<<"Align left:"<<setiosflags(ios::left)<<setprecision(20)<<a<<endl<<endl;
13     cout<<"Right align:"<<setiosflags(ios::right)<<setprecision(20)<<a<<endl<<endl;
14     system("pause");
15     return 0;
16 }

You may not use #include < iomanip >

cout.precision() sets the precision after the decimal point,

cout.width() sets the width,

cout.setf() sets the display format, such as

cout.setf(ios::left) align left

cout.setf(ios::showpoint) displays the decimal point regardless of whether there are decimal places

cout.fill(); Fill if the width is insufficient, such as cout fill('0');

For example, this week's race 1002, if COUT is used, it should be set like this before output.

cout.precision(6);

cout.width(8);

cout.setf(ios::left);

cout.setf(ios::showpoint);

cout.fill('0');

Just cout Precision (6) and cout When setf (IOS:: showpoint), for some reason, if it is 0, it will only be displayed to small

The last five digits of the count, so in order to add a 0 at the end, we need to add three other supplements (part of which is in iomanip):

Long flags() const returns the current format flag.

Long flags (long newflag) sets the format flag to newflag and returns the old format flag.

long setf(long bits) sets the specified format flag bit and returns the old format flag.

long setf(long bits,long field) sets the format flag position specified by the field to bits and returns the old format flag

long unsetf(long bits) clears the format flag bit specified by bits and returns the old format flag.

long fill(char c) sets the fill character, which is blank by default.

char fill() returns the current fill character.

int precision(int val) sets the precision to val, controls the significant bit of the output floating-point number, and returns the old value.

int precision() returns the old precision value.

int width(int val) sets the width of the display data (domain width), and returns the old domain width.

int width() returns only the current field width. The default width is 0. At this time, the insertion operation can be displayed according to the minimum width of the data

data

dec decimal input and output

Hex hex input / output

oct octal input and output

For example, use cout < < hex < < i < < endl; That is, the variable i can be output in hexadecimal format.

ws extract white space characters

Brush new flow

resetiosflags(long) please remove the specific format flag bit

setiosflags(long) sets a specific format flag bit

setfill(char) sets the fill character

setprecision(int) sets the precision of the output floating-point number

setw(int) sets the field width format variable

1: The standard input function cin does not know whether it is a function or not. It represents the standard input device - keyboard. It belongs to stream, and its usage is the same as that of stream. That is: cin > > variable;

For a little explanation, multiple input variables can be written in one line, such as: CIN > > x > > y > > Z; This writing is not allowed, but is not good-looking. If it is a different variable type, it will be mindless. People don't know what to input except you

Therefore, we usually give a prompt before the input statement. Please enter ×××, Let people know what this variable does. In addition, this function does not need to take the address symbol "&" and specify the variable type. Do not confuse it with scanf. Of course, he does not check whether the variable input is legal. For ex amp le:

int i; cout<<"please input a number:" cin>>i; cout<<"i="<<i<<endl;

If you input a character such as' a ', it will not be checked, but the result you output is not correct. If you check it manually. Of course, like scanf, if you enter illegal variable values inside the loop, you will also fall into an endless loop. As follows:

  View Code

1 /*An example of an illegal input variable falling into an endless loop*/
 #include <iostream.h>
int main() 
{ 
    int i; 
    while(i!=-1) 
    { 
        cout<<"i=" cin>>i; /*Please enter a character other than 'a'*/ 
        cout<<endl;   
     } 
}

In the previous program, if you enter illegal, you will fall into an endless loop.

There is one solution: put cin > > I; If the statement is moved to the statement to judge the loop, if the variable you enter is illegal, it will jump out of the loop. cin is separated by spaces. Take a look at the following examples:

/*A space separation makes the input variable less than the desired value*/ 
#include <iostream.h> 
int main() 
{ 
    char str[20]; 
    cout<<"please input a string:";
    cin>>str; /*You try typing "hello word"*/ 
    cout<<endl<<"str="<<str; 
}

Can you see what the result is? All you get is str=hello. Why? Because cin is separated by spaces, when you enter a space, he thinks that the following input does not belong here and that it should be given to the following variables. In addition, when the string you enter is larger than the allocated space, overflow will occur. Of course, there are functions input in the whole line, including spaces, which will be learned in the future.

2, The standard output function cout says that cout is a function, which is the same as cin. I don't know if it's right. He represents the standard output device - display. In fact, this function has been used many times before. Let's format the output through an example. You can experience this example, which is much more flexible than printf. First, we can display our data in hexadecimal, octal and hexadecimal, as follows:

  View Code

 1 /*An example of hexadecimal output*/
 2 #include<iostream.h>
 3 void main()
 4 {
 5     int x=30, y=300, z=1024;
 6     cout<<x<<' '<<y<<' '<<z<<endl; //Output in decimal
 7     cout.setf(ios::showbase | ios::uppercase); //Set base indicator output and uppercase output in numeric values
 8     cout<<x<<' '<<y<<' '<<z<<endl;
 9     cout.unsetf(ios::showbase | ios::uppercase); //Cancels the output of base indicators and uppercase letters in numeric values
10     cout.setf(ios::oct); //Set to octal output. This setting is always valid if it is not cancelled
11     cout<<x<<' '<<y<<' '<<z<<endl; //Output in octal
12     cout.setf(ios::showbase | ios::uppercase); //Set base indicator output and uppercase output in numeric values
13     cout<<x<<' '<<y<<' '<<z<<endl;
14     cout.unsetf(ios::showbase | ios::uppercase); //Cancels the output of base indicators and uppercase letters in numeric values
15     cout.unsetf(ios::oct); //Cancel the octal output setting and restore the decimal output
16     cout.setf(ios::hex); //Set to hexadecimal output
17     cout<<x<<' '<<y<<' '<<z<<endl;
18     cout.setf(ios::showbase | ios::uppercase); //Set base indicator output and uppercase output in numeric values
19     cout<<x<<' '<<y<<' '<<z<<endl;
20     cout.unsetf(ios::showbase | ios::uppercase); //Cancels the output of base indicators and uppercase letters in numeric values
21     cout.unsetf(ios::hex); //Cancel the hexadecimal output setting and restore the decimal output
22     cout<<x<<' '<<y<<' '<<z<<endl;
23 }


 

We use cout Setf () sets the output format, using cout Unsetf() cancels formatting. It can be seen that whether the base indication is set or not at the time of output

The symbol ios:: showbase is useless. When outputting octal, it is preceded by 0, while hexadecimal is preceded by 0X. For the uppercase output of letters in numerical values, only hexadecimal

Useful, we should use it according to the situation in the future. Of course, as we said earlier, there is another way to format the output, that is, to use the manipulation operator, as follows,

  View Code

 1 /*An example of hexadecimal output*/
 2 #include<iomanip.h>
 3 void main()
 4 {
 5     int x=30, y=300, z=1024;
 6     cout<<x<<' '<<y<<' '<<z<<endl; //Output in decimal
 7     cout<<oct<<x<<' '<<y<<' '<<z<<endl; //Output in octal
 8     cout<<setiosflags(ios::showbase); //Set base indicator
 9     cout<<x<<' '<<y<<' '<<z<<endl; //Still output in octal
10     cout<<resetiosflags(ios::showbase); //Cancel base indicator
11     cout<<hex<<x<<' '<<y<<' '<<z<<endl; //Output in hexadecimal
12     cout<<setiosflags(ios::showbase | ios::uppercase);
13     //Set the base indicator and the uppercase output of letters in the value,
14     cout<<x<<' '<<y<<' '<<z<<endl; //Still output in hexadecimal
15     cout<<resetiosflags(ios::showbase | ios::uppercase);
16     //Cancels uppercase output in base indicators and numeric values
17     cout<<x<<' '<<y<<' '<<z<<endl; //Still output in hexadecimal
18     cout<<dec<<x<<' '<<y<<' '<<z<<endl; //Output in decimal
19 }

We can also output the same result with the above program, which shows its flexibility. We now output the following text:

Chapter I

1.1 what is C language one

1.11 history of C language fifty-eight

Chapter II

There are many methods. We can write as follows:

  View Code

 1 /*An example of using fill, width and alignment*/
 2 #include <iostream.h>
 3 void main()
 4 {
 5     cout<<"Chapter I"<<endl;
 6     cout<<" ";
 7     cout.setf(ios::left); //Set the alignment to left
 8     cout.width(7); //Set the width to 7, which is not enough to be filled with spaces
 9     cout<<"1.1";
10     cout<<"What is? C language";
11     cout.unsetf(ios::left); //Cancel the alignment mode and use the default right mode
12     cout.fill('.'); //Set filling method
13     cout.width(30); //Set the width, which is only useful for the next output
14     cout<<1<<endl;
15     cout<<" ";
16     cout.width(7); //Set width
17     cout.setf(ios::left); //Set the alignment to left
18     cout.fill(' '); //Set fill, the default is blank
19     cout<<"1.11";
20     cout<<"C History of language";
21     cout.unsetf(ios::left); //Cancel alignment
22     cout.fill('.');
23     cout.width(30);
24     cout<<58<<endl;
25     cout.fill(' ');
26     cout<<"Chapter II"<<endl;
27 }

We set the width for many times to make our spacing consistent and use the alignment method to make our data aligned and beautiful

. We also use the filling method. It is also possible for us to use manipulation operators.

  View Code

 1 /*An example of using fill, width and alignment*/
 2 #include <iomanip.h>
 3 void main()
 4 {
 5     cout<<"Chapter I"<<endl;
 6     cout<<" ";
 7     cout<<setiosflags(ios::left)<<setw(7); //Set the width to 7 and the left alignment
 8     cout<<"1.1";
 9     cout<<"What is? C language";
10     cout<<resetiosflags(ios::left); //Cancel alignment
11     cout<<setfill('.')<<setw(30)<<1<<endl; //The width is 30 and the filling is'. ' output
12     cout<<setfill(' '); //Restore padding to spaces
13     cout<<" ";
14     cout<<setw(7)<<setiosflags(ios::left); //Set the width to 7 and the left alignment
15     cout<<"1.11";
16     cout<<"C History of language";
17     cout<<resetiosflags(ios::left); //Cancel alignment
18     cout<<setfill('.')<<setw(30)<<58<<endl; //The width is 30 and the filling is'. ' output
19     cout<<setfill(' ')<<"Chapter II"<<endl;
20 }

We output the same effect, but according to my character, I prefer to format the output with manipulators. Finally, let's look at the format output of floating-point numbers,

Examples are as follows:

  View Code

 1 /*About the format of floating point numbers*/
 2 #include <iostream.h>
 3 void main()
 4 {
 5     float f=2.0/3.0,f1=0.000000001,f2=-9.9;
 6     cout<<f<<' '<<f1<<' '<<f2<<endl; //Normal output
 7     cout.setf(ios::showpos); //Force a + sign before a positive number
 8     cout<<f<<' '<<f1<<' '<<f2<<endl;
 9     cout.unsetf(ios::showpos); //Cancel plus sign before positive number
10     cout.setf(ios::showpoint); //Force display of invalid 0 after decimal point
11     cout<<f<<' '<<f1<<' '<<f2<<endl;
12     cout.unsetf(ios::showpoint); //Suppress invalid 0 after decimal point
13     cout.setf(ios::scientific); //Scientific notation
14     cout<<f<<' '<<f1<<' '<<f2<<endl;
15     cout.unsetf(ios::scientific); //Cancel scientific notation
16     cout.setf(ios::fixed); //Output display by point
17     cout<<f<<' '<<f1<<' '<<f2<<endl;
18     cout.unsetf(ios::fixed); //Cancel point output display
19     cout.precision(18); //The accuracy is 18 and the normal is 6
20     cout<<f<<' '<<f1<<' '<<f2<<endl;
21     cout.precision(6); //Accuracy restored to 6
22 }

Similarly, we can also use manipulators to achieve the same functions:

  View Code

 1 /*About the format of floating point numbers*/
 2 #include <iomanip.h>
 3 void main()
 4 {
 5     float f=2.0/3.0,f1=0.000000001,f2=-9.9;
 6     cout<<f<<' '<<f1<<' '<<f2<<endl; //Normal output
 7     cout<<setiosflags(ios::showpos); //Force a + sign before a positive number
 8     cout<<f<<' '<<f1<<' '<<f2<<endl;
 9     cout<<resetiosflags(ios::showpos); //Cancel plus sign before positive number
10     cout<<setiosflags(ios::showpoint); //Force display of invalid 0 after decimal point
11     cout<<f<<' '<<f1<<' '<<f2<<endl;
12     cout<<resetiosflags(ios::showpoint); //Suppress invalid 0 after decimal point
13     cout<<setiosflags(ios::scientific); //Scientific notation
14     cout<<f<<' '<<f1<<' '<<f2<<endl;
15     cout<<resetiosflags(ios::scientific); //Cancel scientific notation
16     cout<<setiosflags(ios::fixed); //Output display by point
17     cout<<f<<' '<<f1<<' '<<f2<<endl;
18     cout<<resetiosflags(ios::fixed); //Cancel point output display
19     cout<<setprecision(18); //The accuracy is 18 and the normal is 6
20     cout<<f<<' '<<f1<<' '<<f2<<endl;
21     cout<<setprecision(6); //Accuracy restored to 6
22 }

In c/c + + system, in addition to the standard input and output, more input functions are provided.

The writing functions mainly include getch(), getche(), getchar(), CIN get(),putch(),putchar(),cout. put(),gets(),cin. getline(),puts().

In addition, there are some operations to buffer so that the buffer does not affect the correct operation of the program, such as CIN putback(),fflush(stdin),cout. flush(). Let's give a brief explanation.

1. getch() and getche(), non buffered input, read a character from the keyboard. The characters read in by getch() are not displayed. Yes, conio H support.

 2,cin.get(),getchar(), buffered input, read a character from the keyboard and display it. Getchar () is defined by stdio H support, CIN Get() by iostream H support.

3. Push () and putchar(), non buffered output, output a character to the display. Push() by conio H support, putchar() is supported by stdio H support.

 4,cout.put(), buffered output, outputting a character to the display. By iostream H support.

5. Gets () and CIN Geline(), buffered input, reads a string (including spaces, excluding the last carriage return), and gets() is generated by stdio H support, CIN Getline() is created by iostream H support.

6. puts(), non buffered output, and output a string, which is generated by stdio H support.

7,cin.putback() returns a character to the input buffer.

8. fflush(stdin) to clear the input buffer. Unable to clear CIN Get() and other operations.

9,cout.flush(), clear the output buffer. Here, let's talk a little about the input / output buffer, which is a space set to reduce the interruption caused by program access io. When the program meets a refresh condition, the buffer will be cleaned up. The specific conditions are:

1. Input buffer A. when the program requires input, press enter. b. End of program encountered. c. Next input statement encountered. d. In case of clear buffer operation e, buffer overflow 2, output buffer a, output buffer overflow B, in case of the next input statement C, flush the buffer to force the clear

Example 2 control the output format with control characters

  View Code

 1 #include <iostream>
 2 #Include < iomanip > / / don't forget to include this header file
 3 using namespace std;
 4 int main()
 5 {  int a;
 6    cout<<"input a:";
 7    cin>>a;
 8    cout<<"dec:"<<dec<<a<<endl; //Output integer in hexadecimal form above
 9    cout<<"hex:"<<hex<<a<<endl; //Output integer a in hexadecimal form
10    cout<<"oct:"<<setbase(8)<<a<<endl;//Output integer a in octal form
11    char *pt="China";         //pt points to the string "China"
12    cout<<setw(10)<<pt<<endl; //Specify a field width of 10 and output a string
13    cout<<setfill('*')<<setw(10)<<pt<<endl;//Specify the field width of 10, output the string, and fill the blank space with "*"
14    double pi=22.0/7.0; //Calculate pi value
15    cout<<setiosflags(ios::scientific)<<setprecision(8);//Output in exponential form, 8 decimal places
16    cout<<"pi="<<pi<<endl; //Output pi value
17    cout<<"pi="<<setprecision(4)<<pi<<endl;//Change to 4 decimal places
18    cout<<"pi="<<setiosflags(ios::fixed)<<pi<<endl;//Output in decimal form
19    return 0; 
20 }

The operation results are as follows:

inputa: 34 (enter the value of a)

dec: 34 (decimal form)

hex: 22 (hex)

oct: 42 (octal form)

China (domain width is 10)

*****China (the field width is 10, and the blank is filled with '*')

pi=3.14285714e+00 (output in exponential form, 8 decimal places)

pi=3.1429e+00) (enter small in exponential form, 4 decimal places)

pi=3.143 (output in decimal form, the tip is still 4)

Topics: C++ iOS