- Asked 2/10
- 2073 Shrawan · 3 marks
- 2072 Chaitra · 3 marks
ios class functions and flags for formatted I/O
Short answer
ios functions width(n) sets next field width; precision(n) sets digits; fill(c) sets pad char; setf(flags) and unsetf(flags) manage flags. Format flags include left/right, dec/oct/hex, showbase, showpoint, showpos, fixed/scientific, uppercase, boolalpha.
What are the different ios class functions and flags that are used for formatted I/O operation? Explain with usage.
The ios class (base of all stream classes) provides member functions and format flags to control formatted I/O.
Member functions
| Function | Use |
|---|---|
width(n) | Sets minimum field width for the next output only |
precision(n) | Sets number of digits (decimal places with fixed) |
fill(ch) | Sets padding character |
setf(flags) | Turns on format flags |
unsetf(flags) | Turns off format flags |
Format flags (used with setf)
| Flag | Effect |
|---|---|
ios::left, ios::right, ios::internal | Justification in field |
ios::dec, ios::oct, ios::hex | Number base |
ios::showbase | Shows 0x or 0 prefix |
ios::showpoint | Shows trailing decimal point/zeros |
ios::showpos | Shows + for positive numbers |
ios::fixed, ios::scientific | Floating point notation |
ios::uppercase | Upper case in hex/exponent |
ios::boolalpha | Prints true/false |
Usage
#include <iostream>
using namespace std;
int main() {
cout.fill('*');
cout.width(10);
cout.setf(ios::left);
cout << "Ram" << endl; // Ram*******
cout.unsetf(ios::left);
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout.width(10);
cout << 3.14159 << endl; // ******3.14
cout.setf(ios::hex, ios::basefield);
cout.setf(ios::showbase);
cout << 255 << endl; // 0xff
return 0;
}
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- ios functions and manipulators in stream I/O · Object Oriented Programming, chapter 8
- Time class: +, <= and << overloading · Object Oriented Programming, chapter 5
- City class with operator overloading · Object Oriented Programming, chapter 5
- Distance class relational operators · Object Oriented Programming, chapter 5
- Abstract Student class program · Object Oriented Programming, chapter 7
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- I/O functions used with data files · Computer Programming, chapter 10 · asked 2×
- Formatted vs unformatted I/O · Computer Programming, chapter 4 · asked 4×
- Source coders used in speech coding · Wireless Communication, chapter 6
- Video rental shop class diagram · Object Oriented Analysis and Design, chapter 2