- Asked 2/10
- 2070 Chaitra · 10 marks
- 2069 Chaitra · 5 marks
Features for formatting output
Short answer
Output formatting uses three mechanisms: (1) ios member functions (width, precision, fill, setf); (2) format flags (left/right, dec/hex, fixed/scientific, showpos); (3) manipulators (setw, setfill, setprecision, endl). Example: cout << setw(8) << setfill('*') << 42;
List the features that are used in formatting the output. Explain each with example.
C++ provides three groups of features to format output:
iosclass member functionsiosformat flags (withsetf()/unsetf())- Manipulators (
<iomanip>and<iostream>)
1. ios member functions
width(n)– minimum field width, applies to the next item only.precision(n)– number of significant digits (decimals withfixed).fill(c)– padding character for unused field width.setf(),unsetf()– set/clear flags.
cout.width(8); cout.fill('#'); cout << 42; // ######42
cout.precision(3); cout << 3.14159; // 3.14
2. Format flags
- Justification:
ios::left,ios::right,ios::internal - Base:
ios::dec,ios::oct,ios::hex, withios::showbase - Floating point:
ios::fixed,ios::scientific,ios::showpoint - Others:
ios::showpos,ios::uppercase,ios::boolalpha
cout.setf(ios::showpos);
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << 7.5; // +7.50
cout.setf(ios::hex, ios::basefield);
cout << 255; // ff
3. Manipulators
setw(n),setfill(c),setprecision(n),setiosflags(f),resetiosflags(f)endl,ends,flush,dec,oct,hex,left,right,fixed,scientific
cout << setw(10) << setfill('*') << left << "Hi" << endl; // Hi********
cout << hex << 255 << dec << " " << 255 << endl; // ff 255
Complete example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << left << setw(10) << "Item"
<< right << setw(8) << "Price" << endl;
cout << left << setw(10) << "Book"
<< right << setw(8) << fixed << setprecision(2) << 250.5 << endl;
cout << left << setw(10) << "Pen"
<< right << setw(8) << 15.0 << endl;
return 0;
}
Output:
Item Price
Book 250.50
Pen 15.00
Difference in use
width()andsetw()affect only the next value; the others stay until changed.- Manipulators can be chained inside one
coutstatement;iosfunctions need separate statements.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- IA features; 3 op-amp IA output voltage · Advanced Electronics, chapter 4
- I/O functions used with data files · Computer Programming, chapter 10 · asked 2×
- CC amplifier Rin, Rout and why it is used · Electronics Devices and Circuit, chapter 2
- Why 8051 / its operational features · Embedded System, chapter 9 · asked 2×