Managing Output with Manipulators in C++

Well, when I started studying C++ or you can say when I was forced to study CPP I was like already I have Maths, Physics and Chemistry to study so why this shitty extra burden on my shoulders.


But that subject which I was forced to study or having no other option instead of studying CPP became my passion now.


Anyways that's a hell of a story! So, this piece of reading will give you an explanation about what are manipulators and how they are implemented in CPP.


Manipulators



By the name you might have already thought that this is going to be something related to manipulation of something. Well, you are on a right track So, you already got an idea what it is about I would like to make it clear that what is that "something".


That something is nothing but Input and Output operations.


Well, in this post we will be focusing mainly on Managing Output with Manipulators.


Lets, start the boring thing!


The header file iomanip provides a set of functions called manipulators which as I said are used to manipulate the output formats.


Some manipulators are more convenient to use as compared to the same used in the class ios.(don't get confused if you don't know about ios class)


They are more flexible to implement because we can use two or more manipulators using a chain statement.


got confused? No problem!


Let me show you an example.


cout << manipulator1 << manipulator2 << manipulator3 << x ; // x is any variable having any variable


cout << manipulator1 << manipulator2 << manipulator3 << y ; // y is any variable having any variable


this is useful when you want to display several columns of output.


Well some of the most commonly used manipulators are


setw (int a) - it is used to set the width of the output to a.


setprecision - (int b) it is used to set the floating point precision to d.


Similarly,


setfill(int c)  - used to set the fill character to c.


setiosflags (long f) - to set the format flag f.


resetiosflags (long f) - to clear the flag specified by f.


endl  - to insert a new line and flush stream.



Well, that was a hell lot of to remember don't worry let's go through some examples to make it more easy to understand.




Example:



cout<< setw(8) << 12345;



This statement prints the value 12345 right- justified i.e, (___12345)


where that underscores are spaces.


if you want to shift the result to the left of the output then you can use setiosflags operation


cout << <<setw(8) << set setiosflags( ios : : left ) << 12345;


Hope you guys got that, if you have any question ask in the comment section below i will try to reply you asap. 

Comments

Post a Comment

Popular posts from this blog

What is sniffing?

Creating a bootable USB.