Saturday 25 April 2015

Formatted Console I/O operations

A Common requirement is to reserve an area of the screen for a field, without knowing the number of characters the data of that field will occupy. To do this there must be a provision for alignment of fields to left or right, or padded with some characters. C++ supports a wide variety of features to perform input or output in different formats.

They include the following:

? Ios stream class member functions and flags
? Standard manipulators
? User-defined manipulators

ios class functions and flags

width() function

specifies the required number of fields to be used while displaying the output value.

Syntax

Int width(void);
Int width(int );

The first form returns the current width setting whereas, the second sets the width to the
specified integer value and returns the previous width.

Precision() function

Specifies the number of digits to be displayed after the decimal point.

Syntax

Int percision(void);
Int precision(int );

By default, the precision size is six. This function must be accessed using objects of the ios class. It sets the precision and returns the previous setting. Unlike width() the precision() must be reset for each data item being output if new precision is desired.

Fill() function

Specifies a character to be used to fill the unused are of a field. By default, fills blank space character. It is member function of ios class and is used to specify the character to be displayed in the unused portion of the display width.

Syntax

Int fill(void);
Int fill(char);

By default, blank character is displaye d in the unused portion if the display width is larger than that required by the value.

Setf() function

C++ provides a mechanism to set the printing of results in the left-justified form, scientific notation etc.

The member function of the ios class, setf() is used to set flags and bit-fields that control the output. It has the following two forms.

Long setf(long setbits, long field);
Long setf(long setbits);

Where setbits is one of the flags defined in the class ios. It specifies the format action required for the output, and field specifies the group to which the formatting flag belongs. Both the forms return the previous settings. The flags, bit-fields when set with setf() and their actions is shown in table.



The following table shows that some of flag value without bit fields for the setf function.





No comments:

Post a Comment