Radix and Base Conversion
graph TD
A[Numeric Formatting] --> B[Decimal]
A --> C[Hexadecimal]
A --> D[Octal]
A --> E[Binary]
Manipulator |
Purpose |
Example |
std::hex |
Hexadecimal display |
Convert to base-16 |
std::dec |
Decimal display |
Convert to base-10 |
std::oct |
Octal display |
Convert to base-8 |
Floating-Point Precision Control
#include <iostream>
#include <iomanip>
void demonstratePrecisionControl() {
double value = 3.14159265358979;
// Default precision
std::cout << "Default: " << value << std::endl;
// Fixed precision
std::cout << "Fixed (2 decimals): "
<< std::fixed << std::setprecision(2)
<< value << std::endl;
// Scientific notation
std::cout << "Scientific: "
<< std::scientific
<< value << std::endl;
}
Alignment and Field Width Techniques
Width and Padding Strategies
#include <iostream>
#include <iomanip>
void demonstrateAlignment() {
int numbers[] = {42, 123, 7};
// Right-aligned with width
std::cout << "Right Alignment:\n";
for (int num : numbers) {
std::cout << std::setw(10) << std::right << num << std::endl;
}
// Left-aligned with padding
std::cout << "Left Alignment:\n";
for (int num : numbers) {
std::cout << std::setw(10) << std::left << num << std::endl;
}
}
#include <iostream>
#include <iomanip>
#include <vector>
void complexFormatting() {
std::vector<std::pair<std::string, double>> data = {
{"Product A", 15.75},
{"Product B", 24.50},
{"Product C", 8.25}
};
std::cout << std::left
<< std::setw(15) << "Product Name"
<< std::setw(10) << "Price"
<< std::endl;
std::cout << std::string(25, '-') << std::endl;
for (const auto& item : data) {
std::cout << std::left
<< std::setw(15) << item.first
<< std::fixed
<< std::setprecision(2)
<< std::setw(10) << item.second
<< std::endl;
}
}
Best Practices
- Choose appropriate precision for your data
- Use consistent formatting across your application
- Consider performance when applying complex formatting
- Excessive formatting can impact performance
- Use manipulators judiciously
- Profile your code when using complex formatting techniques
At LabEx, we recommend mastering these formatting techniques to create more readable and professional C++ output.