Creating my own manipulators (formatting flags for streams)

This is a discussion on Creating my own manipulators (formatting flags for streams) within the C++ Programming forums, part of the General Programming Boards category; Hello, I know that to format output I can use a number of predefined manipulators such as std::boolalpha, std::hex, etc. ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    1

    Question Creating my own manipulators (formatting flags for streams)

    Hello,

    I know that to format output I can use a number of predefined manipulators such as std::boolalpha, std::hex, etc. and use them such as:

    Code:
    int myNumber = 0;
    cout << boolalpha << myNumber << endl;
    and that would print false.

    I would like to write my own manipulators to format a couple of things that cannot be done with the usual ones, however I've been unable to locate info about how to do this.

    In particular I would like to be able to store in a text file certain words and map them to bool values in the program, for example

    Code:
    bool dropTheBomb = true;
    cout << my_manipulator << dropTheBomb << endl;
    should print "Yeah!!", and the other way around: I would like to read "Yeah!!" from a string and store it as a bool

    Does anybody know how to do this?

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    manipulators are made from classes which are friends with an overloaded operator<<(). here's a simple example converting bool's to custom strings.

    edit : You know what? Never code when it's past midnight and you have bags under your eyes!

    Re-Post : manipulator code.

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    class myManip
    {
        friend ostream& operator<< (ostream&, myManip&);
        string out;
    
    public:
        myManip(bool b)
        { 
            out=( b?"Yeah" : "Nah!" ); 
        }
    };
    
    ostream& operator<< (ostream& os, myManip& mm)
    {   return os<< mm.out;    }
    
    int main()
    {
        cout << myManip(true);
        cin.get();
    }
    Last edited by Bench82; 03-14-2006 at 05:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  2. dos game help
    By kwm32 in forum Game Programming
    Replies: 7
    Last Post: 03-28-2004, 05:28 PM
  3. Question about formatting flags
    By dpro in forum C Programming
    Replies: 2
    Last Post: 12-24-2002, 03:46 PM
  4. Creating a student grade book-how?
    By Hopelessly confused in forum C Programming
    Replies: 5
    Last Post: 10-03-2002, 08:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21