You can create your own stream manipulators. Figure 13.11 shows how to create and use new nonparameterized stream manipulators bell
(lines 8–11), carriageReturn
(lines 14–17), tab
(lines 20–23) and endLine
(lines 27–30). For output stream manipulators, the return type and parameter must be of type ostream &
. When line 35 inserts the endLine
manipulator in the output stream, function endLine
is called and line 29 outputs the escape sequence
and the flush
manipulator (which flushes the output buffer) to the standard output stream cout
. Similarly, when lines 35–44 insert the manipulators tab
, bell
and carriageReturn
in the output stream, their corresponding functions—tab
(line 20), bell
(line 8) and carriageReturn
(line 14) are called, which in turn output various escape sequences.
1 // Fig. 13.11: fig13_11.cpp
2 // Creating and testing user-defined, nonparameterized
3 // stream manipulators.
4 #include <iostream>
5 using namespace std;
6
7 // bell manipulator (using escape sequence a)
8 ostream& bell( ostream& output )
9 {
10 return output << 'a'; // issue system beep
11 } // end bell manipulator
12
13 // carriageReturn manipulator (using escape sequence
)
14 ostream& carriageReturn( ostream& output )
15 {
16 return output << '
'; // issue carriage return
17 } // end carriageReturn manipulator
18
19 // tab manipulator (using escape sequence )
20 ostream& tab( ostream& output )
21 {
22 return output << ' '; // issue tab
23 } // end tab manipulator
24
25 // endLine manipulator (using escape sequence
and flush stream
26 // manipulator to simulate endl)
27 ostream& endLine( ostream& output )
28 {
29 return output << '
' << flush; // issue endl-like end of line
30 } // end endLine manipulator
31
32 int main()
33 {
34 // use tab and endLine manipulators
35 cout << "Testing the tab manipulator:" << endLine
36 << 'a' << tab << 'b' << tab << 'c' << endLine;
37
38 cout << "Testing the carriageReturn and bell manipulators:"
39 << endLine << "..........";
40
41 cout << bell; // use bell manipulator
42
43 // use carriageReturn and endLine manipulators
44 cout << carriageReturn << "-----" << endLine;
45 } // end main
Testing the tab manipulator:
a b c
Testing the carriageReturn and bell manipulators:
-----.....
18.223.33.157