C + + cout formatted output function

Source: Internet
Author: User
Tags setf

This article explains how to use cout for advanced format output operations in C + +, including various counts (precision) outputs for numbers, left or right alignment, capitalization, and so on. With this article, you can completely detach from scanf/printf and use only cout to do all the formatting input and output functions you need (from a non-performance perspective). Further, you can use these formatting actions on <sstream>, <fstream> instead of the sprintf and fprintf functions. For the convenience of description, the following is an example of cout.

Overview cout is an iostream instance provided by the STL library, with all functions and member data of the Ios_base base class. The SETF/UNSETF function and the flags function can be directly used for formatting operations. Cout maintains a current format state, the SETF/UNSETF function appends or deletes the specified format in the current format state, and flags replaces the current format state with the specified format. Cout provides the following parameters for this function (optional format):
  • iOS::d ec represents integers in 10 binary
  • Ios::hex An integer in 16 binary notation
  • ios::oct An integer in 8 binary notation
  • Ios::showbase adds a prefix to an integer that represents its binary
  • Ios::internal Inserts the required number of padding characters between the sign bit and the value to align the ends of the string
  • Ios::left Inserts a padding character at the end of the string to align the left side of the string
  • Ios::right Inserts a padding character in front of the string to align the string to the right
  • Ios::boolalpha represents the value of type bool as TRUE or flase, instead of 1 or 0
  • ios::fixed the number of character points in the normal fixed-point format (non-scientific counting method)
  • ios::scientific The number of points is processed by scientific notation (with exponential field)
  • Ios::showpoint force insertion of a decimal point in a decimal number represented by a floating-point number (by default, the integer represented by a floating-point number does not display a decimal point)
  • Ios::showpos Force to add a + sign before a positive number
  • IOS::SKIPWS ignores leading spaces (primarily for input streams, such as CIN)
  • Ios::unitbuf emptying the cache after inserting (each output) operation
  • ios::uppercase Force uppercase letters
Each of these formats occupies a separate one, so you can use the ' | ' The (bitwise OR) operator is used in combination. Calling the SETF/UNSETF or flags formatting is generally done as follows:

    • cout.setf (ios::right | ios::hex);//set 16 binary right align
    • cout.setf (Ios::right, Ios::adjustfield);//Cancel other alignment, set to right align



SETF can accept one or two parameters, the version of a parameter is set to the specified format, two parameters are in the version, and the latter parameter specifies the format of the deletion. The three defined combination formats are:
    • Ios::adjustfield to the gill-type combination bit
    • Ios::basefield binary combination bit
    • Ios::floatfield A combination of floating-point representations
After formatting, all output using cout will be executed in the specified format state. However, if you need to mix multiple formats in a single output, it is inconvenient to use cout's member functions to handle them. STL also provides a set of <iomanip> libraries to meet this use. The <iomanip> library sets and deletes each format in a function-level package of the same name, such as a fixed function, you can use an Ostream object as an argument, and internally call the SETF function to set the ios::fixed format before returning the original object. In addition <iomanip> provides convenient format control functions such as Setiosflags, SetBase, Setfill, SETW, setprecision, etc., which are described below. Most of the sample code will be used to <iomanip&gt, so the header files included by default are:

#include <iomanip> #include <iostream>



The indentation aligns the output to the specified width and requires the use of SETW in Ios::right, Ios::left, ios::internal, and Iomanip. Where SETW is used to specify the alignment width of the content to output. The result of the following two pieces of code is exactly the same, preceded by a floating-point number-456.98, followed by a string "The End" and a newline character "Endl".

Code One:

#include <iomanip> #include <iostream>using namespace Std;int main (void) {    cout.flags (ios::left);// Left align    cout << setw << -456.98 << "The End" << Endl;    Cout.flags (ios::internal); Justify    cout << SETW (Ten) << -456.98 << "The End" << Endl;    Cout.flags (Ios::right); Right-aligned    cout << setw << -456.98 << "The End" << Endl;    return 0;}



Code two:

#include <iomanip> #include <iostream>using namespace Std;int main (void) {    cout << left << SETW << -456.98 << "The End" << Endl; Left align    cout << internal << setw << -456.98 << "The End" << Endl;//Justify    cout < < right << setw << -456.98 << "The End" << Endl; Right-aligned    return 0;}



Results:
-456.98 the End
-456.98The End

-456.98the End

The extra point here is that the SETW function controls the alignment position with the current fill character, and the default padding character is a space. The fill character can be set by the Setfill of <iomanip>, such as the following code with the character "0" as the fill character:


#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
cout << Setfill (' 0 ') << setw (Ten) << 45698 << Endl;
return 0;
}

Results: 0000045698

The format of integer output integer is in different binary numbers: Ios::hex (16), iOS::d EC (10), IOS::OCT (8), or force its output symbol (positive plus "+" prefix), for 16 output can also be used with iOS:: Uppercase make all letters in uppercase. The code examples are as follows:

#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
COUT.SETF (Ios::showpos | ios::uppercase);
cout << hex << setw (4) << << setw << -12 << Endl;
cout << Dec << setw (4) << << setw << -12 << Endl;
cout << Oct << SETW (4) << << setw ( -12) << << Endl;
COUT.UNSETF (Ios::showpos | ios::uppercase);
cout << hex << setw (4) << << setw << -12 << Endl;
cout << Dec << setw (4) << << setw << -12 << Endl;
cout << Oct << SETW (4) << << setw ( -12) << << Endl;
return 0;
}



Results:


C FFFFFFF4
+12-12
14 37777777764
C FFFFFFF4
12-12
14 37777777764

The SetBase function of <iomanip> can also be set to three of integers, with parameters of 8, 10, and 16, but it is more complex to use than the method above, unless it is a special code specification (some specifications require that constants be avoided directly as expressions). It is generally not recommended to use SetBase. In addition, you can also use Ios::showbase to precede an integer with a prefix that represents the binary, the code is as follows:

#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
cout << showbase << setw (4) << hex << << setw (4) << Oct << << Endl;
cout << noshowbase << setw (4) << hex << << setw (4) << Oct << << Endl ;
return 0;
}


Results:

0x20 040
20 40
The showbase/noshobase in the above code can also be replaced with the cout SETF, the result is exactly the same:


#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
COUT.SETF (ios::showbase);
cout << SETW (4) << hex << << setw (4) << Oct << + << Endl;
COUT.UNSETF (ios::showbase);
cout << SETW (4) << hex << << setw (4) << Oct << + << Endl;
return 0;
}

The decimal number can be divided into two types of formats, one is the fixed-point expression "ios::fixed" (without exponential field) and the other is scientific notation means "ios::scientific" (with exponential field). Used with the setprecision of <iomanip>, you can represent the number of reserved digits (rounding) after the specified decimal point. The sample code is as follows:

#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
COUT.SETF (ios::fixed);
cout << setprecision (0) << 12.05 << Endl;
cout << setprecision (1) << 12.05 << Endl;
cout << setprecision (2) << 12.05 << Endl;
cout << setprecision (3) << 12.05 << Endl;
COUT.SETF (ios::scientific, Ios::floatfield);
cout << setprecision (0) << 12.05 << Endl;
cout << setprecision (1) << 12.05 << Endl;
cout << setprecision (2) << 12.05 << Endl;
cout << setprecision (3) << 12.05 << Endl;
return 0;
}

Results:
12
12.1
12.05
12.050
1.205000e+001
1.2e+001
1.21e+001
1.205e+001

It is important to note that sometimes the result of rounding is incorrect due to machine accuracy problems. This problem generally requires manual correction, as shown in the following code example:

#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
cout << Fixed << setprecision (1) << 2.05 << Endl;
cout << Fixed << setprecision (1) << 2.05 + 1e-8 << Endl;
return 0;
}
Results:
2.0
2.1
Four, the string string output processing is mainly aligned, which in the second part has been introduced, the following main introduction of the string input method. For the sake of convenience, we use the <string> library. When entering a string, you can use the Getline function provided by the <string> library to read the entire row of data. The Getline function has two versions, the first version has two parameters, the first parameter specifies the input stream (such as CIN), and the second parameter specifies a string object. Getline reads the characters entered on the screen until the newline character "\ n" is encountered, the second version has three parameters, the first two are the same as the previous one, and the third parameter is the specified ending character. Note that Getline does not read into the default or specified end character, but the position read after the call has skipped the end character. Call the sample code as follows:

#include <iomanip>
#include <iostream>
#include <string>
using namespace Std;
int main (void) {
String str1, str2;
Getline (CIN, STR1);
Cin >> str2;
cout << str1 << endl << str2 << Endl;
return 0;
}

Input:
Abc
Abc
Results:
Abc
Abc

Five, buffer due to the call system functions on the screen display character is very slow, so cin/cout in order to speed up the use of buffer technology, the rough is to temporarily not output the specified characters, but stored in the buffer, at the right time to output to the screen at once. If the use of C + + input/output streams to manipulate characters is not a problem of synchronization, but if you want to mix with the C standard Library Stdio library functions, you must handle the buffer carefully. If you want to use it with scanf and printf, be sure to add Cout.sync_with_stdio () before calling cout, and synchronize the settings with Stdio, otherwise the output's data order will be confusing.

Flush and Endl will write the contents of the current buffer immediately to the screen, while unitbuf/nounitbuf can disable or enable the buffer. The sample code is as follows:

#include <iomanip>
#include <iostream>
using namespace Std;
int main (void) {
cout << 123 << flush << 456 << Endl;
cout << unitbuf << 123 << nounitbuf << 456 << Endl;
return 0;
}

Results:
123456
123456
Vi. integrated use of the sample code:

#include <iomanip>
#include <iostream>
#include <string>
using namespace Std;
struct commodity {string Name; int Id; int Cnt; double price;};
int main (void) {
Commodity cmd[] = {
{"Fruit", 0x101, 50, 5.268},
{"Juice", 0x102, 20, 8.729},
{"Meat", 0x104, 30, 10.133},
};
cout << left << setw (8) << ' NAME ' << right << setw (8) << "ID";
cout << Right << setw (8) << ' COUNT ' << right << setw (8) << ' price ' << Endl;
for (int i = 0; i < sizeof (cmd)/sizeof (cmd[0]); ++i) {
cout << left << setw (8) << Cmd[i]. Name;
cout << Right << hex << showbase << SETW (8) << Cmd[i]. Id;
cout << Dec << noshowbase << SETW (8) << Cmd[i]. Cnt;
cout << Fixed << setw (8) << setprecision (2) << cmd[i]. Price << Endl;
}
return 0;
}



Results:


NAME ID COUNT Price
Fruit 0x101 50 5.27
Juice 0x102 20 8.73
Meat 0x104 30 10.13


C + + cout formatted output function

Related Article

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.