Stream Manipulation
Stream Manipulators Overview
Stream manipulators are powerful tools in C++ that allow you to control the formatting and behavior of input and output operations.
graph TD
A[Stream Manipulators] --> B[Formatting]
A --> C[State Control]
A --> D[Numeric Representation]
#include <iostream>
#include <iomanip>
int main() {
int number = 42;
// Decimal representation
std::cout << std::dec << number << std::endl;
// Hexadecimal representation
std::cout << std::hex << number << std::endl;
// Octal representation
std::cout << std::oct << number << std::endl;
return 0;
}
Floating-Point Precision
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.14159265358979;
// Default precision
std::cout << pi << std::endl;
// Fixed precision
std::cout << std::fixed << std::setprecision(2) << pi << std::endl;
// Scientific notation
std::cout << std::scientific << pi << std::endl;
return 0;
}
Width and Alignment Manipulators
Manipulator |
Description |
setw() |
Set field width |
left |
Left-align output |
right |
Right-align output |
setfill() |
Set padding character |
Alignment Example
#include <iostream>
#include <iomanip>
int main() {
// Right-aligned with width and fill
std::cout << std::right << std::setw(10) << std::setfill('*') << 42 << std::endl;
// Left-aligned
std::cout << std::left << std::setw(10) << "LabEx" << std::endl;
return 0;
}
#include <iostream>
int main() {
bool flag = true;
// Default boolean output
std::cout << flag << std::endl;
// Textual boolean output
std::cout << std::boolalpha << flag << std::endl;
return 0;
}
Custom Stream Manipulators
#include <iostream>
#include <iomanip>
// Custom manipulator
std::ostream& emphasize(std::ostream& os) {
return os << "[IMPORTANT] ";
}
int main() {
std::cout << emphasize << "LabEx is an excellent learning platform" << std::endl;
return 0;
}
State Control Manipulators
Manipulator |
Description |
skipws |
Skip whitespace |
noskipws |
Don't skip whitespace |
ws |
Extract whitespace |
Best Practices
- Use manipulators for consistent formatting
- Choose appropriate precision for numeric output
- Create custom manipulators for repetitive formatting
- Be aware of performance implications
LabEx Learning Tip
Mastering stream manipulators is crucial for professional C++ programming. LabEx provides interactive environments to practice these techniques effectively.