Introduction to Stream Manipulators
Stream manipulators in C++ provide powerful ways to control output formatting, allowing precise control over how data is displayed.
Manipulator |
Purpose |
Header |
std::setw() |
Set field width |
<iomanip> |
std::setprecision() |
Control decimal precision |
<iomanip> |
std::fixed |
Fixed-point notation |
<iomanip> |
std::scientific |
Scientific notation |
<iomanip> |
std::hex |
Hexadecimal output |
<iomanip> |
Numeric Notation Manipulators
#include <iostream>
#include <iomanip>
int main() {
double value = 123.456789;
// Fixed-point notation
std::cout << std::fixed
<< std::setprecision(2)
<< value << std::endl;
// Scientific notation
std::cout << std::scientific
<< value << std::endl;
return 0;
}
Base Conversion Manipulators
graph LR
A[Numeric Base] --> B[Decimal]
A --> C[Hexadecimal]
A --> D[Octal]
A --> E[Binary]
Base Conversion Example
#include <iostream>
#include <iomanip>
int main() {
int number = 255;
// Decimal representation
std::cout << "Decimal: "
<< std::dec << number << std::endl;
// Hexadecimal representation
std::cout << "Hexadecimal: "
<< std::hex << number << std::endl;
// Octal representation
std::cout << "Octal: "
<< std::oct << number << std::endl;
return 0;
}
#include <iostream>
#include <iomanip>
int main() {
bool flag = true;
// Default boolean output
std::cout << "Default: " << flag << std::endl;
// Textual boolean output
std::cout << std::boolalpha;
std::cout << "Textual: " << flag << std::endl;
return 0;
}
#include <iostream>
#include <iomanip>
int main() {
// Combining multiple manipulators
std::cout << std::setfill('*')
<< std::setw(10)
<< std::left
<< std::hex
<< 255
<< std::endl;
return 0;
}
Best Practices for LabEx Developers
- Always include
<iomanip>
for advanced formatting
- Use manipulators to enhance code readability
- Reset manipulator states when needed
- Combine manipulators for complex formatting
- Be aware of performance implications
Manipulator State Management
#include <iostream>
#include <iomanip>
int main() {
// Save and restore stream state
std::ios_base::fmtflags original_flags =
std::cout.flags();
// Perform formatting
std::cout << std::hex << 255 << std::endl;
// Restore original formatting
std::cout.flags(original_flags);
return 0;
}