How do you create a manipulator that can be used even inside setf? [ANSWERED] | Sololearn: Learn to code for FREE!


How do you create a manipulator that can be used even inside setf? [ANSWERED]

I have a vector class and I want to provide a feature to allow the user to see the vector either in the terms of i, j and k, or display its magnitude and the angles with the coordinate axes. I wanted to do both of these using the ostream operator, so I decided to make a manipulator. I searched the net and made this: ostream& ijk_not(ostream& os); // In this I turn a variable true, thats all. Now I was able to do: cout<<ijk_not<<vec1; But now I want this to work: cout.setf(ijk_not); How to do this?


12/9/2017 7:14:48 AM

Kinshuk Vasisht

15 Answers

New Answer


Note : I agree my 'so called manipulator' is not at all a manipulator. Its just an ostream function that tricks the class to do things my way. I opened the iomanip header's library and found that setf accepts a variable of type ios_base, and it performs a bitwise xor/or (I don't remember) on this flag and perhaps thats what switches it on. But I cannot declare an object of type ios_base. I need help to create a successful manipulator! Please help!


@Gordie I am sorry. I had an exam. Ill just post the class. Thank you very much for the solution!


@Gordie I actually renamed ijk_not to simple, and the declaration now looks like this: const ios_base::fmtflags simple = static_cast<ios_base::fmtflags>(0x0); // This flag is the else version.


@Gordie The fmtflag works as expected with setf. But when I do : cout<<simple<<v1; The program instead of setting the flag and then printing the data as per the format prints the flag as it is (the data). Thus the flag doesn't work for both the things at the same time. Either I could get it working with setf, or with cout. Isn't there a way to do both?


Here is the code. I have added both the manipulator and the format flag, but t seems there is an error as the names are causing ambiguity. But I never saw this happen with boolalpha, fixed or any other flags like these.


I wished to know something. When I print the cout.flags() bitwise, I get a certain number. But when I perform the setf function and after checking the change reprint the bit pattern after some cout operations, I get a different pattern from the one I saw after setf. Why? Now, If this continue, and I decide to use the 5th bit for my use, how will I know whether the change in my bit was genuinely caused by setf or just a cout operation? And secondly, I can focus on a single bit for manipulation, right?


@Gordie Thanks a lot! You made my day!