Create simple parameterized input and output manipulators. - C++ File Stream

C++ examples for File Stream:cout

Description

Create simple parameterized input and output manipulators.

Demo Code

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class indent {// w  w  w . j  av  a  2 s . c  o  m
   int len;
   public:
   indent(int i) { len = i; }
   friend ostream &operator<<(ostream &stream, indent ndt);
};
// Create an inserter for objects of type indent.
ostream &operator<<(ostream &stream, indent ndt) {
   for(int i=0; i <  ndt.len; ++i) stream << " ";
   return stream;
}
class skipchar {
   char ch;
   public:
   skipchar(char c) { ch = c; }
   friend istream &operator>>(istream &stream, skipchar sc);
};
// Create an extractor for objects of type skipchar.
istream &operator>>(istream &stream, skipchar sc) {
   char ch;
   do {
      ch = stream.get();
   } while(!stream.eof() && ch == sc.ch);
   if(!stream.eof()) stream.unget();
   return stream;
}
int main() {
   string str;
   // Use indent to indent output.
   cout << indent(9) << "This is indented 9 places.\n" << indent(9) << "So is this.\n" << indent(18) << "But this is indented 18 places.\n\n";
   // Use skipchar to ignore leading zeros.
   cout << "Enter some characters: ";
   cin >> skipchar('0') >> str;
   cout << "Leading zeros are skipped. Contents of str: " << str << "\n\n";
   // Use indent on an ostringstream.
   cout << "Use indent with a string stream.\n";
   ostringstream ostrstrm;
   ostrstrm << indent(5) << 128;
   cout << "Contents of ostrstrm:\n" << ostrstrm.str() << endl;
   return 0;
}

Result


Related Tutorials