iomanip
library is useful for manipulating output
setw(width)
function used to output text in a fixed number of characters
// Put this with other include statements #include <iomanip> // Output each literal in a column of 7 spaces right justified cout << setw(7) << "You" << endl; cout << setw(7) << "say" << endl; cout << setw(7) << "goodbye" << endl;Output:
You say goodbye
std::left
changes the alignment to the left
// Make left justified cout << left; cout << setw(7) << "I" << setw(7) << "say" << setw(7) << "hello";Output:
I say hello
std::fixed
makes all floating-point numbers
display their decimal points (no scientific notation)
std::setprecision(places)
rounds numbers to the specified number decimal places
double a = 1234567.159; cout << a << endl; // 1.23457e+006 cout << fixed; cout << a << endl; // 1234567.159000 cout << setprecision(2); cout << a << endl; // 1234567.16
const
before declaration and always assign a value
// Correct const double PI = 3.14; // Wrong! const double PI; PI = 3.14; // Using a constant area = PI * radius * radius;
Example | Equivalent |
---|---|
x++; |
x = x + 1; |
x--; |
x = x - 1; |
x += 2; |
x = x + 2; |
x -= 2; |
x = x - 2; |
x *= 2; |
x = x * 2; |
x /= 2; |
x = x / 2; |
x %= 2; |
x = x % 2; |