Formatted I/O in C++
Introduction
Formatted I/O in C++ refers to the process of controlling the format of input and output operations. This can include specifying the width of output fields, setting the number of decimal places for floating-point numbers, and aligning text. In this tutorial, we will cover various techniques and functions used to format I/O in C++.
Basic Output Formatting
The most common way to format output in C++ is using the stream manipulators provided by the iostream library. Let's look at some basic examples:
Example:
#include <iostream> using namespace std; int main() { int num = 123; cout << "Default: " << num << endl; cout << "Hexadecimal: " << hex << num << endl; cout << "Octal: " << oct << num << endl; cout << "Decimal: " << dec << num << endl; return 0; }
Hexadecimal: 7b
Octal: 173
Decimal: 123
Setting Field Width
You can set the width of the output field using the setw
manipulator from the <iomanip>
library.
Example:
#include <iostream> #include <iomanip> using namespace std; int main() { int num = 123; cout << setw(10) << num << endl; return 0; }
123
Floating-Point Formatting
For floating-point numbers, you can control the precision and format using various manipulators.
Example:
#include <iostream> #include <iomanip> using namespace std; int main() { double num = 123.456789; cout << fixed << setprecision(2) << num << endl; cout << scientific << setprecision(2) << num << endl; return 0; }
1.23e+02
Aligning Text
You can align text to the left or right using the left
and right
manipulators.
Example:
#include <iostream> #include <iomanip> using namespace std; int main() { cout << left << setw(10) << "Left" << endl; cout << right << setw(10) << "Right" << endl; return 0; }
Right
Customizing Fill Characters
You can customize the fill character used to pad the width of the output field using the setfill
manipulator.
Example:
#include <iostream> #include <iomanip> using namespace std; int main() { cout << setfill('*') << setw(10) << 123 << endl; return 0; }
Combining Manipulators
You can combine multiple manipulators to achieve complex formatting.
Example:
#include <iostream> #include <iomanip> using namespace std; int main() { double num = 123.456; cout << setfill('-') << setw(10) << right << fixed << setprecision(2) << num << endl; return 0; }
Conclusion
Formatted I/O in C++ provides a powerful way to control the appearance of your program's output. By using manipulators, you can set field widths, precision, fill characters, and alignment to display your data in a clear and organized manner.