User-defined Manipulators
Learn how to create manipulators to output a tab and display a roman number as a decimal.
We'll cover the following...
Problem
Write a program to create two user-defined manipulators called tab
and roman
. The tab
manipulator should output a \t
to the output stream and the roman
manipulator should receive a roman string as an argument and send its decimal equivalent to the output stream.
Coding solution
Here is a solution to the problem above.
Press + to interact
// User-defined manipulators#include <iostream>std :: ostream& tab ( std :: ostream& o ){return o << "\t" ;}class roman{private :std :: string str ;public :roman ( std :: string s ){str = s ;}friend std :: ostream& operator << ( std :: ostream&, const roman& ) ;} ;std :: ostream& operator << ( std :: ostream& o, const roman& r ){struct key{char ch ;int val ;} ;key z[ ] = {{'m', 1000},{'d', 500},{'c', 100},{'l', 50},{'x', 10},{'v', 5},{'i', 1}} ;int num = 0 ;int prev ;int sz = sizeof ( z ) / sizeof ( z[ 0 ] ) ;for ( int i = 0 ; i < r.str.length ( ) ; i++ ){int j ;for ( j = 0 ; j < sz ; j++ ){if ( z[ j ].ch == r.str[ i ] ){break ;}}num = num + z[ j ].val ;if ( i != 0 && prev < z[ j ].val )num = num - 2 * prev ;prev = z[ j ].val ;}o << num ;return o ;}int main( ){std :: string str1 = "viii" ;std :: string str2 = "mcmxcviii" ;std :: cout << "Roman: " << str1 << tab << "Dec: " << roman ( str1 ) << std :: endl;std :: cout << "Roman: " << str2 << tab << "Dec: " << roman ( str2 ) << std :: endl;return 0 ;}
Explanation
To understand how to develop a zero-argument manipulator we need to understand the internal working of some existing manipulator, say endl
. endl
is simply a function that takes as its argument an ostream
reference. The ...