Translate

Saturday 12 May 2012

Formatted Output in C++



In C++ output can be obtained in formatted form by using escape sequence and manipulators

Escape sequence
As the title suggests escape sequence it varies from normal form for instance ‘n’ represents character n where as ‘\n’ represents new line character. The following table illustrates the escape sequence characters and their purpose.

Escape Sequence
Purpose
\n
New line
\t
Horizontal tab
\a
Beep
\r
Enter key
\b
Tab Backward
\”
To insert double quotes in a string
\’
To insert single quotes in a string
\\
To have the effect of \ with the string
\0
Null character



Manipulators without arguments
They precedes the variable used in an output expression. endl, oct, hex, flush are the manipulators which can be used with the objects.

Manipulator
Purpose
endl
Endline i.e. insert a new line at the end.
oct
Provides octal equivalent.
hex
Provides hexadecimal equivalent.
dec
Provides decimal equivalent.
flush
It clears the output stream.

         Some manipulator requires arguments also. They need the header file <iomanip.h>. They are used
to determine the size of the fraction part, the width of the variables, a character to fill the empty space etc.


setw(n):- The manipulator fixes the width size as n.
a=743;
cout<< “a=”<<setw(5)<<a;
Now  a=__743
_ is blank space here.

setprecision(n):- It fixes the fraction part of a floating value witn n digits.
a=569.645;
cout<< “a=”<<setprecicion(2)<<a;
Now  a=569.65

setfill(c):-This function fills the leftmost blanks of a value with a character ch as a default it uses blank spaces as the character for filling the blanks.
                                   a=743;
                                   cout<< “a=”<< setfill(‘0’) << setw(5) <<a;
                                   Now  a=00743                    

No comments:

Post a Comment

Total Pageviews