iomanip is another include library that you can include at the top of your program along with
iostream. It is (likely) shorthand for "Input/Output Manipulator" since it lets you manipulate how to write to cout. It allows us to format text a lot more easily. Observe:
Example: Aligning text to the right
Code (C++)
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int number1 = 2;
int number2 = 23;
int number3 = 435;
cout << "Number 1: " << setw(4) << right << number1 << endl;
cout << "Number 2: " << setw(4) << right << number2 << endl;
cout << "Number 3: " << setw(4) << right << number3 << endl;
}
This program would print out 3 numbers, but it would make sure that the number field is set to a width of 4 characters, and would make sure it would print from the right. Its output would look like this:
Output
Number 1: 2
Number 2: 23
Number 3: 435
To clarify what I meant, if you set the width to 4 and print from the right, you are given the following room to work with:
Output
Number 1:
^^^^
Then afterwards, it will print from the right of that field of 4.
Output
Number 1: 2
^^^^
Example: Forcing 2 decimal places on a double
iomanip also allows us to set the number of decimal places printed out. That can be done with two operators: fixed and setprecision(). Here is an example:
Code (C++)
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double value = 0.123456;
cout << fixed << setprecision(2) << value << endl;
}
I already spoiled what the result would be:
Output
0.12
Why do we need "fixed"? Isn't "setprecision()" good enough? Well... not exactly. If we do not print out in "fixed" notation, C++ will lean toward printing out in scientific notation. Plus then "setprecision" will go toward the number of numbers printed out as opposed to the number of decimal places printed out.