当前位置:网站首页>C + + cout format output complete strategy

C + + cout format output complete strategy

2020-11-25 21:02:27 RioTian

When I write the algorithm problem, I suddenly find that I forget the basic C++:cout Formatted output , Pull out the old one C++ Take a look at the study notes again .

Part of the content comes from the tutorial :C Chinese language network ( A great website )

Sometimes you want to output in a certain format , For example, output integers in hexadecimal , Output floating-point numbers with two decimal places , Press the 6 The width of the number output , When the width is not enough, fill the left side 0, wait .C In language printf() Function to % The format controller at the beginning , for example %X、%.2f、%6d etc. ;C++ Medium cout Objects use stream operators ( You can also call it a format controller ) Or member functions to control .

Use stream operators

C++ The commonly used output stream operators are shown in the table 1 Shown , They're all in the header file iomanip As defined in ; To use these flow operators , Must contain the header file .

Be careful :“ Flow operators ” The asterisk in the column * It's not part of the operator , The asterisk indicates that without using any operator , It is equivalent to using this operator . for example , By default , Integers are output in decimal form , It is equivalent to using dec operator .

Flow operators do use
*dec Output integers in decimal form Commonly used
hex Output integer in hexadecimal form |
oct Output integers in octal form |
fixed Output floating point numbers as ordinary decimal numbers |
scientific Output floating-point numbers in the form of scientific notation |
left Align left , That is, when the width is not enough, the padding character will be added to the right |
*right Right alignment , That is, when the width is not enough, the padding character will be added to the left |
setbase(b) Set the base of the output integer ,b=8、10 or 16 |
setw(w) Specifies that the output width is w Characters , Or input a string w Characters |
setfill(c) In the case of specified output width , When the output width is not enough, use characters c fill ( The default is to fill in with spaces ) |
setprecision(n) Set the precision of the output floating-point number to n. In the use of non fixed And not scientific Mode output ,n That is, the number of digits with the most significant number , If the number of significant digits exceeds n, Then the decimal part is rounded up to five people , Or automatically become a scientific plan Number output and keep a total of n Significant digits . In the use of fixed The way and scientific Mode output ,n Is the number of digits that should be retained after the decimal point . |
setiosflags(flag) Set an output format flag to 1 |
resetiosflags(flag) Set an output format flag to 0 |
boolapha hold true and false The output is a string Not commonly used
*noboolalpha hold true and false Output is 0、1 -
showbase Outputs a prefix that represents the base number of a number -
*noshowbase Do not output the base number of the number . The prefix of -
showpoint Always output decimal point -
*noshowpoint The decimal point is displayed only when the decimal part exists -
showpos Show... In nonnegative values + -
*noshowpos Don't show... In nonnegative values + -
*skipws Skip white space on input -
noskipws Don't skip blank characters when typing -
uppercase In hexadecimal numbers A~E. If the output prefix , Then the prefix outputs 0X, Output in scientific counting E -
*nouppercase In hexadecimal numbers a~e. If the output prefix , Then the prefix outputs 0x, Output in scientific counting e. -
internal The sign of the number ( The sign ) Align left within specified width , The value is right to Qi , The middle is filled with fill characters . -

'|': For commonly used ,'-': It's not commonly used

How to use the stream operator

The way to use these operators is to use the operators with << and cout Continuous use . for example :

cout << hex << 12 << "," << 24;

The function of this statement is to specify that the last two numbers are output in hexadecimal form , So the output is :

c, 18

setiosflags() operator

setiosflags() The operator is actually a library function , It takes some flags as parameters , These signs can be in iostream The following values are defined in the header file , They have the same meaning as operators of the same name .

mark Records do use
ios::left The output data is aligned to the left in a wide range of the local area
ios::right The output data is aligned to the right within a wide range of the domain
ios::internal The sign bit of the value is left aligned within the field width , Align values right , The middle is filled with fill characters
ios::dec Set the base of the integer to 10
ios::oct Set the base of the integer to 8
ios::hex Set the base of the integer to 16
ios::showbase Force the cardinality of the output integer ( Octal number 0 start , Hexadecimal number 0x Lead )
ios::showpoint Forces the output of the floating-point number of small points and mantissa 0
ios::uppercase In the form of scientific notation E And in hexadecimal output letters in uppercase
ios::showpos A positive number shows “+” Number
ios::scientific Floating point number scientific notation format output
ios::fixed Fixed point format for floating point numbers ( Decimal form ) Output
ios::unitbuf Refresh all streams after each output
ios::stdio Clear after each output stdout, stderr

In fact, all of these symbols have only one bit 1, And all the other bits are 0 The integer of .

Multiple signs can be used | Operator join , Means to set at the same time . for example :

cout << setiosflags(ios::scientific|ios::showpos) << 12.34;

The output is :

+1.234000e+001

If two conflicting signs are set at the same time , If you set it first setiosflags(ios::fixed), And then set up setiosflags(ios::scientific), The result may be that neither marker works . therefore , In the setting of a certain sign , When you have to set other signs that contradict it , You should use resetiosflags Clear the original logo . For example, the following three sentences :

cout << setiosflags(ios::fixed) << 12.34 << endl;
cout << resetiosflags(ios::fixed) << setiosflags(ios::scientific | ios::showpos) << 12.34 << endl;
cout << resetiosflags(ios::showpos) << 12.34 << endl;  // Clear the flag to output a positive sign 

The output is :
12.340000
+1.234000e+001
1.234000e+001

Comprehensive examples

On the use of flow operators , Take a look at the procedure below .

#include <iomanip>
#include <iostream>
using namespace std;
int main() {
    int n = 141;
    // 1)  In hexadecimal 、 Decimal system 、 Octal output successively  n
    cout << "1)" << hex << n << " " << dec << n << " " << oct << n << endl;
    double x = 1234567.89, y = 12.34567;
    // 2) Retain 5 Significant digits 
    cout << "2)" << setprecision(5) << x << " " << y << " " << endl;
    // 3) Keep after the decimal point 5 position 
    cout << "3)" << fixed << setprecision(5) << x << " " << y << endl;
    // 4) Scientific counting outputs , And keep it after the decimal point 5 position 
    cout << "4)" << scientific << setprecision(5) << x << " " << y << endl;
    // 5) Nonnegative numbers show a positive sign , The output width is 12 character , If the width is not enough, use  *  fill 
    cout << "5)" << showpos << fixed << setw(12) << setfill('*') << 12.1
         << endl;
    // 6) Non negative numbers do not show a positive sign , The output width is 12 character , If the width is not enough, fill it with filling characters on the right 
    cout << "6)" << noshowpos << setw(12) << left << 12.1 << endl;
    // 7) The output width is  12  character , If the width is not enough, fill the left with filling characters 
    cout << "7)" << setw(12) << right << 12.1 << endl;
    // 8) When the width is not enough , Negative signs and numbers are left and right , Fill in the middle with filler characters 
    cout << "8)" << setw(12) << internal << -12.1 << endl;
    cout << "9)" << 12.1 << endl;
    return 0;
}

The output of the program is :

1)8d 141 215
2)1.2346e+06 12.346
3)1234567.89000 12.34567
4)1.23457e+06 1.23457e+01
5)***+12.10000
6)12.10000****
7)****12.10000
8)-***12.10000
9)12.10000

It should be noted that ,setw() The function of the operator is one-time , That is, only the next output will be affected . Use... Every time you need to specify the output width setw(). So you can see , The first 9) The output of the line is not used setw(), The width of the output is no longer the one specified earlier 12 Characters .

When reading a string ,setw() It can also affect cin act . For example, the following procedure :

#include <iomanip>
#include <iostream>
using namespace std;
int main() {
    string s1, s2;
    cin >> setw(4) >> s1 >> setw(3) >> s2;
    cout << s1 << "," << s2 << endl;
    return 0;
}

Input :
1234567890

The output of the program is :
1234,567

explain setw(4) Make it read in s1 when , Read in only 4 Characters , The subsequent setw(3) Make it read in s2 When you read in 3 Characters .

setw() be used for cin when , Again, it only affects the next input .

Thinking questions :setw() How did it come true , To be able to communicate with cout The hyphen is used to specify the output width ? Check for your own compiler iomanip The header file , Then write a function and setw() Exactly the same mysetw().

call cout Member function of

ostream Class has some member functions , adopt cout Calling them can also be used to control the format of the output , Its function is the same as the flow operator , As shown in the table 3 Shown .

Member functions The same function of the flow operator explain
precision(n) setprecision(n) Set the precision of the output floating-point number to n.
width(w) setw(w) Specifies that the output width is w Characters .
fill(c) setfill (c) In the case of specified output width , When the output width is not enough, use characters c fill ( The default is to fill in with spaces ).
setf(flag) setiosflags(flag) Set an output format flag to 1.
unsetf(flag) resetiosflags(flag) Set an output format flag to 0.

setf and unsetf Function is used to flag, And setiosflags and resetiosflags The same thing is used .

The usage of these member functions is very simple . For example, the following three line program :

cout.setf(ios::scientific);cout.precision(8);cout << 12.23 << endl;

The output is :
1.22300000e+001

版权声明
本文为[RioTian]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/11/20201125210007750f.html

随机推荐