Loading lessons...
Streams, Formatted I/O & Manipulators (including User-Defined Manipulators)
Streams, Formatted I/O & Manipulators (including User-Defined Manipulators)
C++ does input and output through streams: objects that carry a sequence of bytes between the program and a device (keyboard, screen, file, string). This lesson covers the stream class hierarchy, unformatted I/O (get, put, getline, write), formatted I/O with ios member functions and manipulators, and how to write your own manipulators.
1. Streams
A stream is a sequence of bytes. It acts as a source from which input data is obtained (an input stream) or a destination to which output data is sent (an output stream). The program works with the stream; the stream hides the details of the actual device, so the same code can write to the screen or to a file.
When a C++ program starts, four stream objects are opened automatically:
| Object | Class | Connected to | Buffered? |
|---|---|---|---|
cin | istream | standard input (keyboard) | yes |
cout | ostream | standard output (screen) | yes |
cerr | ostream | standard error (screen) | no: appears immediately |
clog | ostream | standard error (screen) | yes |
2. The Stream Class Hierarchy
The C++ stream class hierarchy
| Class | Role |
|---|---|
ios (ios_base) | the base of all stream classes: format flags, error state, width, precision, fill. A virtual base class of istream and ostream |
streambuf | the buffer that moves data to and from the device; ios holds a pointer to it |
istream | input: >>, get(), getline(), read() |
ostream | output: <<, put(), write() |
iostream | both input and output; derived from istream and ostream (multiple inheritance) |
ifstream, ofstream, fstream | file streams (Lesson 36) |
istringstream, ostringstream, stringstream | streams on a string in memory |
Because ios is a virtual base, an iostream object contains only one copy of the format state, a real-world use of the diamond solution from Lesson 30.
3. Unformatted Input/Output
| Function | Task |
|---|---|
cin >> x | reads a value; skips leading whitespace; stops at whitespace |
cin.get(ch) | reads one character, including spaces and newlines |
cout.put(ch) | writes one character |
cin.getline(buf, size) | reads a line (up to size - 1 characters) into a char array; discards the newline |
cout.write(buf, n) | writes the first n characters of buf |
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char line[50];
cin.getline(line, 50); // reads "Hello IPU world" with spaces
cout << "Line read: " << line << endl;
int chars = 0;
char c;
cin.get(c); // read the next line character by character
while (c != '\n') {
cout.put(c); // echo it
chars++;
cin.get(c);
}
cout << endl << "Characters: " << chars << endl;
const char* text = "Programming";
cout.write(text, 7); // first 7 characters only
cout << endl;
cout.write(text, strlen(text)).put('!').put('\n'); // write and put can be chained
return 0;
}Input:
Hello IPU world
a b cOutput:
Line read: Hello IPU world
a b c
Characters: 5
Program
Programming!4. Formatted Output with ios Member Functions
| Function | Task |
|---|---|
width(n) | minimum field width for the next item only |
precision(n) | number of digits after the decimal point (in fixed or scientific mode) or significant digits (otherwise) |
fill(ch) | character used to pad unused positions (default space) |
setf(flag, group) | set a formatting flag |
unsetf(flag) | clear a formatting flag |
setf call | Effect |
|---|---|
setf(ios::left, ios::adjustfield) | left-justify (ios::right is the default, ios::internal pads after the sign) |
setf(ios::fixed, ios::floatfield) | fixed-point notation: 3.140000 |
setf(ios::scientific, ios::floatfield) | exponent notation: 3.14e+00 |
setf(ios::showpoint) | always show the decimal point and trailing zeros |
setf(ios::showpos) | print + before positive numbers |
setf(ios::hex, ios::basefield) | print integers in hex (ios::oct, ios::dec) |
setf(ios::showbase) | show 0x / 0 before hex/octal numbers |
setf(ios::uppercase) | upper-case X and E |
#include <iostream>
using namespace std;
int main() {
cout.width(10);
cout << 543 << "|" << endl; // width applies to 543 only
cout.fill('*');
cout.width(10);
cout << 543 << "|" << endl;
cout.setf(ios::left, ios::adjustfield);
cout.width(10);
cout << "Name" << "|" << endl;
cout.fill(' ');
cout.unsetf(ios::left);
cout.setf(ios::fixed, ios::floatfield);
cout.precision(3);
cout << 3.14159 << " " << 2.5 << endl;
cout.setf(ios::showpos);
cout << 42.0 << endl;
cout.unsetf(ios::showpos);
cout.setf(ios::hex, ios::basefield);
cout.setf(ios::showbase);
cout << 255 << endl;
return 0;
}Output:
543|
*******543|
Name******|
3.142 2.500
+42.000
0xff5. Manipulators
Manipulators are special functions used inside an I/O chain with << or >> to format data. They do the same jobs as the ios member functions but are more convenient, because they can be chained. Manipulators that take arguments are declared in <iomanip>.
| Manipulator | Equivalent ios function | Effect |
|---|---|---|
setw(n) | width(n) | field width for the next item |
setprecision(n) | precision(n) | precision of floating point output |
setfill(ch) | fill(ch) | padding character |
setiosflags(f) | setf(f) | set format flags |
resetiosflags(f) | unsetf(f) | clear format flags |
setbase(b) | number base 8, 10 or 16 | |
endl | newline and flush | |
ends | insert a null character '\0' | |
flush | flush() | flush the output buffer |
ws | skip leading whitespace on input | |
dec, oct, hex | setf(..., ios::basefield) | number base |
left, right, fixed, scientific, showpos, boolalpha | setf(...) | the corresponding flags |
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setw(12) << left << "Item" << setw(8) << right << "Qty" << setw(10) << "Price" << endl;
cout << setfill('-') << setw(30) << "" << setfill(' ') << endl;
cout << fixed << setprecision(2);
cout << setw(12) << left << "Pen" << setw(8) << right << 10 << setw(10) << 12.5 << endl;
cout << setw(12) << left << "Notebook" << setw(8) << right << 3 << setw(10) << 48.75 << endl;
cout << "255 in oct: " << oct << 255 << ", hex: " << hex << 255 << dec << endl;
cout << "bool: " << boolalpha << true << " " << noboolalpha << true << endl;
return 0;
}Output:
Item Qty Price
------------------------------
Pen 10 12.50
Notebook 3 48.75
255 in oct: 377, hex: ff
bool: true 1cout << scientific << setprecision(3) << 123456.789 prints 1.235e+05 (old MinGW compilers on Windows print three exponent digits, 1.235e+005).
ios functions vs manipulators
ios member functions | Manipulators |
|---|---|
called as separate statements: cout.width(5); | used inside the chain: cout << setw(5) << x; |
| return the previous setting, so it can be saved and restored | return the stream (for chaining) |
| no extra header | parameterised ones need <iomanip> |
| cannot be user-defined in the chain | user-defined manipulators can be created |
6. User-Defined Manipulators
We can create our own manipulators to package a format we use often.
Without arguments
A manipulator without arguments is simply a function that takes and returns a stream reference:
When you write cout << name, the overloaded << for function pointers calls name(cout).
#include <iostream>
#include <iomanip>
using namespace std;
ostream& unit(ostream& out) { // prints a unit label
out << " Rs";
return out;
}
ostream& currency(ostream& out) { // a reusable money format
out << fixed << setprecision(2) << setw(10);
return out;
}
ostream& tab(ostream& out) {
out << '\t';
return out;
}
ostream& line(ostream& out) {
out << "--------------------" << endl;
return out;
}
int main() {
cout << line;
cout << "Fee" << tab << currency << 85000.0 << unit << endl;
cout << "Hostel" << tab << currency << 72000.5 << unit << endl;
cout << line;
return 0;
}Output:
--------------------
Fee 85000.00 Rs
Hostel 72000.50 Rs
--------------------With an argument
A manipulator that takes an argument, like setw(n), is implemented with a small class: the "manipulator" is a function that returns an object storing the argument, and << is overloaded for that class.
#include <iostream>
using namespace std;
class Repeat { // stores the arguments
public:
char ch;
int count;
Repeat(char c, int n) : ch(c), count(n) {}
};
Repeat repeat(char c, int n) {
return Repeat(c, n);
} // the manipulator
ostream& operator<<(ostream& out, const Repeat& r) { // applies it
for (int i = 0; i < r.count; i++) {
out << r.ch;
}
return out;
}
int main() {
cout << repeat('=', 12) << endl;
cout << repeat(' ', 4) << "Result" << endl;
cout << repeat('=', 12) << endl;
return 0;
}Output:
============
Result
============7. Stream Error States
Every stream has state flags that record whether the last operation succeeded.
| Flag | Function | Set when |
|---|---|---|
goodbit | good() | everything is fine |
eofbit | eof() | end of input/file reached |
failbit | fail() | an operation failed, e.g. letters typed where a number was expected |
badbit | bad() | a serious, unrecoverable error |
clear() resets the flags so the stream can be used again. A stream used in a condition (if (cin >> x)) is true when the read succeeded.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n; // input is "abc": reading an int fails
if (cin.fail()) {
cout << "Not a number, fail() = " << cin.fail() << endl;
cin.clear(); // reset the error flags
char junk[20];
cin >> junk; // throw away the bad word
}
cin >> n; // next word is "25"
cout << "Read " << n << ", good() = " << cin.good() << endl;
return 0;
}Input:
abc 25Output:
Not a number, fail() = 1
Read 25, good() = 1Key points to remember
- A stream is a sequence of bytes;
cin,cout,cerr(unbuffered),clogare predefined. - Hierarchy:
ios(virtual base) →istream,ostream→iostream; file and string streams derive from these. - Unformatted I/O:
get,put,getline,write. - Formatting:
width,precision,fill,setf/unsetf, or the manipulatorssetw,setprecision,setfill,fixed,left,hex...;width/setwapply to the next item only. - User-defined manipulator:
ostream& name(ostream& os) { ...; return os; }; with arguments, use a helper class and overload<<.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What are streams? Explain the stream class hierarchy in C++. (5 Marks)
- Write: the definition, the four predefined streams, the hierarchy diagram and the class table; mention that
iosis a virtual base. - Q2. What are manipulators? Explain the commonly used manipulators and compare them with
iosfunctions. (10 Marks) - Write: the manipulator table, the bill program with output, and the comparison table.
- Q3. How are user-defined manipulators created? Write a program. (5 Marks)
- Write: the function form without arguments (
currency,unit) and the class-based form with an argument (repeat). - Q4. Explain the unformatted I/O functions
get(),put(),getline()andwrite(). (5 Marks) - Q5. Explain the
iosformat flags withsetf(). (5 Marks)