2. Input and Output In C++ – Object-Oriented Programming with ANSI and Turbo C++

2

CHAPTER

Input and Output in
C++

C
H
A
P
T
E
R

O
U
T
L
I
N
E
—• 2.1 Introduction
—• 2.2 Streams in C++
—• 2.3 Pre-Defined Streams
—• 2.4 Buffering
—• 2.5 Stream Classes
—• 2.6 Formatted and Unformatted Data
—• 2.7 Unformatted Console I/O Operations
—• 2.8 Typecasting with cout Statement
—• 2.9 Member Functions of Istream Class
—• 2.10 Formatted Console I/O Operations
—• 2.11 BIT Fields
—• 2.12 Flags without BIT Field
—• 2.13 Manipulators
—• 2.14 User-Defined Manipulators
—• 2.15 Manipulator with one Parameter
—• 2.16 Manipulators with Multiple Parameters
—• 2.17 Custom Built I/O Objects

2.1 INTRODUCTION

Applications generally involve reading a large amount of data from input devices and sending them to the output devices. Hence to control such operations every language provides a set of in-built functions. C++ supports all Input /Output functions of C. C++ also has library functions. A library is a set of .obj files, which is linked to the program and gives additional support to its functions. A programmer can use the library functions in the programs. The library is also called as iostream library. The difference between C and C++ I/O functions is that C functions do not support object-oriented platform whereas C++ supports it.

2.2 STREAMS IN C++

C++ supports a number of Input/Output (I/O) operations to read and write operations. These C++ I/O functions make it possible for the user to work with different types of devices such as keyboard, disk, tape drivers etc. The stream is an intermediator between I/O devices and the user. The standard C++ library contains the I/O stream functions. The I/O functions are part of the standard library that provides portability to the language itself. A library is nothing but a set of .obj files. It is connected to the user's program.

Stream is flow of data in bytes in sequence. If data is received from input devices in sequence then it is called as source stream and when the data is passed to output devices then it is called as destination stream. It is also referred as encapsulation through streams. The data is received from keyboard or disk and can be passed on to monitor or to the disk. Figure 2.1 describes the concept of stream with input and output devices.

Fig.2.1 Streams and I/O devices

Data in source stream can be used as input data by the program. So, the source stream is also called as input stream. The destination stream that collects output data from the program is known as output stream. The mechanism of input and output stream is illustrated in Figure 2.2.

As mentioned earlier, the stream is an intermediator between I/O devices and the user. The input stream pulls the data from keyboard or storage devices such as hard disk, floppy disk etc. The data present in output stream is passed on to the output devices such as monitor or printer according to the user's choice.

Fig.2.2 C++ Input and output streams

2.3 PRE-DEFINED STREAMS

C++ has a number of pre-defined streams. These pre-defined streams are also called as standard I/O objects. These streams are automatically activated when the program execution starts. Table 2.1 describes the pre-defined streams.

Table 2.1 Predefined C++ stream or I/O global objects

cin Standard input, usually keyboards, corresponding to stdin in C. It handles input from input devices usually from keyboard. The Figure 2.3 indicates frequently used member function with cin object
cout Standard output, usually screen, corresponding to stdout in C. It passes data to output devices such as monitor and printers. Thus, it controls output. The Figure 2.4 indicates frequently used functions with cout object.
clog A fully buffered version of cerr (no C equivalent). It controls error messages that are passed from buffer to the standard error device.
cerr Standard error output, usually screen, corresponding to stderr in C. It controls the unbuffered output data. It catches the errors and passes to standard error device monitor.

A simple program is illustrated using above I/O objects as follows.

Fig.2.3 Frequently used unformatted input functions with cin object

Fig.2.4 Frequently used unformatted output functions with cout object

2.1 Write a program to display message using pre-defined objects.

# include <iostream.h>
# include <conio.h>
                 
void main( ) 
{
    clrscr( );
    cout <<"\nSTREAMS";
    cerr <<"\nSTREAMS";
    clog <<"\nSTREAMS";
}

OUTPUT
STREAMS
STREAMS
STREAMS

Explanation: In this program the pre-defined object cout, cerr, and clog are used to display messages “STREAMS” on the screen.

2.4 BUFFERING

Buffer It is a block of memory used to hold data temporarily. It is always located between a peripheral device and faster computer. Buffers are used to pass data between computer and devices. The buffer increases the performance of the computer by allowing read/write operation in larger chunks. For example, if the size of buffer is N, the buffer can hold N number of bytes of data.

Writing data to the disk is very costly. The read/write operation with disk takes a long time. While these operations are carried out the execution of the program will be slow for few seconds. If the program involves a lot of read and write operations, the program execution speed will be slower. To avoid this problem the stream provides buffer. Buffer holds the data temporarily. The input data is passed on to the stream buffer. The data is not written to the disk immediately till the buffer fills. When the buffer is completely filled the data is written on to the disk. This example is related with the example shown in Figure 2.5.

In Figure 2.5 (a) the level of the steam in the pressure cooker is increasing. The steam is not full, hence the whistle will not blow, and the steam will not be released from the pressure cooker.

In Figure 2.5 (b) the pressure cooker is completely filled. The level of the steam reaches to the top. Due to high-pressure the whistle blows automatically and the steam is released from the pressure cooker.?

Fig.2.5 Working of buffer

After the steam has been released the whistle falls down. Even when the cooker is not completely filled with steam, the steam can be released manually by pulling up the whistle. It is just like flushing the buffer even when the buffer is not completely filled.

2.5 STREAM CLASSES

C++ streams are based on class and object theory. C++ has a number of stream classes that are used to work with console and file operations. These classes are known as stream classes. Figure 2.6 indicates the stream classes. All these classes are declared in the header file iostream.h. The file iostream.h must be included in the program if we are using functions of these classes.

Fig.2.6 (a) Stream classes

Fig. 2.6 (b) Hierarchy of stream classes

As described in Figure 2.6 (a) the classes istream and ostream are derived classes of base class ios. The ios class contains member variable object streambuf.v The streambuf places the buffer. The member function of streambuf class handles the buffer by providing the facilities to flush clear and pour the buffer. The class iostream is derived from the classes istream and ostream by using multiple inheritance. The ios class is a virtual class and this is to avoid ambiguity that frequently appears in multiple inheritance. The chapter on Inheritance describes multiple inheritance and virtual classes.

The ios class has an ability to handle formatted and unformatted I/O operations. The istream class gives support to both formatted and unformatted data. The ostream classes handle the formatting of output of data. The iostream contains functioning of both istream and ostream classes. The classes istream_withassign, ostream_withassign, and iostream_withassign append appropriate assignment operators as shown in Figure 2.5 (b).

2.6 FORMATTED AND UNFORMATTED DATA

Formatting means representation of data with different settings as per the requirement of the user. The various settings that can be done are number format, field width, decimal points etc.

The data accepted or printed with default setting by the I/O function of the language is known as unformatted data. For example, when the cin statement is executed it asks for a number. The user enters a number in decimal. For entering decimal number or displaying the number in decimal using cout statement the user won't need to apply any external setting. By default the I/O function represents number in decimal format. Data handled in such a way is called as unformatted data.

If the user needs to accept or display data in hexa-decimal format, manipulators with I/O functions are used. The data obtained or represented with these manipulators are known as formatted data. For example, if the user wants to display the data in hexa-decimal format then the manipulator can be used as follows.

cout<<hex<<15;

The above statement converts decimal 15 to hexadecimal F.

2.7 UNFORMATTED CONSOLE I/O OPERATIONS

Input and Output Streams

The input stream uses cin object to read data and the output stream uses cout object to display data on the screen. The cin and cout are predefined streams for input and output of data. The data type is identified by these functions using operator overloading of the operators << (insertion operator) and >> (extraction operator). The operator << is overloaded in the ostream class and the operator >> is overloaded in istream class. Figure 2.7 shows the flow of input and output stream.

INPUT STREAM The input stream does read operation through keyboard. It uses cin as object. The cin statement uses >> (extraction operator) before variable name. The cin statement is used to read data through the input device. Its syntax and example are as follows.

Syntax:

cin >>variable

Example:

int v1;

float v2;

char v3;

cin >> v1 >> v2 >> v3…. . >>vn;

Fig.2.7 Working of cin and cout statements

Where v1, v2, and v3 are variable names. The response of the user to this statement would be as per given below.

2 5.4 A // input data

If the user enters data in the manner 2 5.4A, the operator will assign 2 to v1, 5.4 to v2 and a to v3. If the entered data is more than the variable, it remains in the input stream. While entering string, blank spaces are not allowed. More than one variable can be used in cin statement to input data. Such operations are known as cascaded input operations.

Example:

cin>>v1>>v3

where v1 and v2 are variables.

The operator >> accepts the data and assigns it to the memory location of the variables. Each variable requires >> operator. Both these statements should not be included in the bracket. The entered data is separated by space, tab, or enter. Like scanf( ) statement cin does not require control strings like %d for integer, %f for float and so on.

More examples

int weight;
cin>>weight      // Reads integer value

float height;
cin>>height;     // Reads float value

double volume;
cin>>volume;     // Reads double value

char result[10];
cin>>result;     // Reads char string

OUTPUT STREAM The output stream manages output of the stream i.e., displays contents of variables on the screen. It uses << insertion operator before variable name. It uses the cout object to perform console write operation. The syntax and example of cout statements are as follows:

Syntax:

cout<<variable

Example

cout <<v1 <<v2 <<v3…<<vn;

where v1, v2, and v3 are variables. The above statement displays the contents of these variables on the screen. The syntax rules are same as cin. Here, the cout statement uses the insertion operator <<. The cout statement does not use the format specification like %d, %f as used in C, and so on. The cout statement allows us to use all ‘C’ escape sequences like ‘\n’, ‘\t’, and so on.

More examples

int weight; 
cout<<weight;     // Displays integer value

float height; 
cout<<height;     // Displays float value

double volume;
cout<<volume;     // Displays double value

char result[10];
cout<<result;     // Reads char string

The box given below illustrates comparative programs on cout statements.

PROGRAM 2.2 PROGRAM 2.3 PROGRAM 2.4
# include <iostream.h> 
void main( ) 
{ 
cout <<" C PLUS PLUS"; 
}
# include <iostream.h> 
void main( ) 
{ 
char *n="Hello"; 
cout <<n; 
}
# include <iostream.h> 
void main( ) 
{ 
int x=10; 
float f=3.14; 
cout <<x; 
cout <<"\t"; 
cout <<f; 
}

 

OUTPUT C PLUS PLUS OUTPUT Hello OUTPUT 10 3.14
In this program the cout statement displays the message “C PLUS PLUS” on the screen. In this program the string is first assigned to character pointer n. The cout statement displays the contents of variable n. In this program integer and float values are assigned to variables x and f. The cout statement displays values of x and f. “\t” is escape sequence used to insert tab.

2.5 Write a program to accept string through the keyboard and display it on the screen. Use cin and cout statements.

# include <iostream.h>
# include <conio.h>
main( ) 
{
   char name[15]; 
   clrscr( );
   cout <<"Enter Your Name :"; 
   cin >>name;
   cout <<"Your name is "<<name; 
   return 0;
}

OUTPUT
Enter Your Name :Amit
Your name is Amit

Explanation: In the above program, cout statement displays given string on the screen. It is similar to printf( ) statement. The cin statement reads data through the keyboard. It is similar to scanf( ) statement.

2.6 Write a program to read two integers and display them. Use cin and cout statements.

# include <iostream.h>
# include <conio.h>
main( ) 
 {
   int num,num1;
   clrscr( ); 
   cout <<"Enter Two numbers : "; 
   cin >>num>>num1;
   cout <<"Entered Numbers are : "; 
   cout <<num<<"\t"<<num1; 
   return 0;
 }

OUTPUT:
Enter Two numbers : 8 9
Entered Numbers are : 8 9

Explanation: In the above program, the cin statement reads two integers in variables num and num1. The cout statement displays the read numbers. The escape sequence ‘\t’ is used to insert tab between two numbers.

2.7 Write a program to display data using cout statements.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   clrscr( );
   cout <<"================";
   cout<<endl;
   cout <<"Hello";    // prints hello 
   cout<<"\n";
   cout <<123;    // prints 123
   cout <<endl<<3.145;   // prints 3.145
   cout <<endl<<"NUMBER : "<<"\t"<<452; // prints string and value 
   cout <<"\n==== The end =====";
 }

OUTPUT
================
Hello
123
3.145
NUMBER :       452
==== The end =====

Explanation: Explanation of each of the cout statements is as follows.

(a) cout <<“================” – Displays line on the screen.

(b) cout<<endl - Breaks a line.

(c) cout <<“Hello” – Display string “Hello” on the screen.

(d) cout<<“\n” – Breaks a line.

(e) cout <<123;– Displays integer 123.

(f) cout <<endl<<3.145 – Breaks a line and display float number 3.145.

(g) cout <<endl<<“NUMBER : ”<<“\t”<<452 – Breaks a line, display string “number”, insert a tab and integer number 452.

(h) cout <<“\n==== The end =====” – Display the line and string.

2.8 Write a program to display integer, float, char, and string using cout statement.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   int x=5;
   float y=5.2;
   char z='z';
   char city[]="NANDED";
   cout <<"x = "<<x <<" y ="<<y <<" z = "<<z <<endl; 
   cout <<"City = "<<city;
 }

OUTPUT
X = 5 y = 5.2 z = z
City = NANDED

Explanation: In the above program, the statement cout <<“x = “<<x <<“ y =”<<y <<” z = “<<z <<endl displays values of x, y, and z. The statement cout <<“City = “<<city displays the contents of character array city.

2.9 Write a program to input integer, float, char, and string using cin statement and display using cout statement.

# include <iostream.h>
# include <conio.h>

void main( )
 {
   clrscr( ); 
   int x; 
   float y; 
   char z;
   char city[15];
   cout <<"\n Enter integer, float and char "; 
   cin >>x>>y>>z;
   cout <<"\n Enter a string : "; 
   cin >>city;
   cout <<"x = "<<x <<" y ="<<y <<" z = "<<z <<endl; 
   cout <<"City = "<<city;
 }

OUTPUT
Enter integer, float, and char 12 1.2 H
Enter a string : NAGPUR
X = 12 y =1.2 z = H
City = NAGPUR

Explanation: Explanation of the program is as follows:

(a) cout <<“\n Enter integer, float and char ”—Prompts message “Enter integer, float and char”

(b) cin >>x>>y>>z—Accepts integer, float and char and stores in x, y, and z.

(c) cout <<“\n Enter a string: “—Displays message “Enter a string : ”.

(d) cin >>city—Reads string through the keyboard and stores in the array city[15].

(e) cout <<“City = “<<city; displays contents of the array city.

2.8 TYPECASTING WITH cout STATEMENT

Typecasting refers to the conversion of data from one basic type to another by applying external use of data type keywords. The description of typecasting is explained in Chapter 3 (C++ declarations). Programs on typecasting are as follows.

2.10 Write a program to use different formats of typecasting and display the converted values.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   int a=66;
   float f=2.5;
   double d=85.22;
   char c='K';
   clrscr( );
   cout <<"\n int in char format    : "<<(char)a;
   cout <<"\n float in int format   : "<<(int)f;
   cout <<"\n double in char format : "<<(char)d;
   cout <<"\n char in int format    : "<<(int)c;
 } 

OUTPUT
int in char format : B
float in int format : 2
double in char format : U
char in int format : 75

Explanation: In the above program, the variables of int, float, double and char type are declared and initialized. The variable a is initialized with 66, f with 2.5, d with 85.22 and c with character ‘K’.

The first cout statement converts integer value to corresponding character according to ASCII character set and the character B is displayed.

The second cout statement converts float value to integer. The value displayed is 2 and not 2.5. When type cast format (int) is used, the decimal portion of float value is removed and only integer part is considered.

In the third statement the double value is converted to character. The number 85.22 are converted to integer and then character. The char data type is more or less similar to int data type except one difference that the char data type ranges from 128 to 127, which requires one byte in the memory.

The last statement converts character to int. The value of ‘K’ is 75 when printed as an integer. The format (int) converts char to int.

In Figure 2.8, 65 is an integer and it is converted to character A by using typecasting format (char). Table 2.2 describes various typecasting formats and their output results.

Fig.2.8 Typecasting integer

Table 2.2 Typecasting formats

Typecasting formats Outputs Conversion
cout <<(char)65; A int to char
cout <<(int)‘A’; 65 char to int
cout <<(int)5.22; 5 float to int
cout <<(char)78.33; N float to char
cout<<(double)123445338.33; 1.234453e+08 float to double
cout<<(unsigned)-1; 65535 signed to unsigned

2.11 Write a program to display data using typecasting.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   int x=77; 
   float y=5.1252; 
   char z=‘A’; 
   char city[15];
   cout <<" x = "<<(char)x<<endl; 
   cout <<" y = "<<(int)y <<endl; 
   cout <<" z = "<<(int)z;
}

OUTPUT
x = M
y = 5
z = 65

Explanation: Consider the following statements:

int x=77—Declares integer variable x and initializes it with 77.

float y=5.1252—Declares float variable y and initialize it with 5.1252.

char z = ‘A’; —Declares character variable z and initializes it with character ‘A’.

To display the contents on the screen following statements are used:

cout <<“ x = “<<(char)x<<endl—Variable x is an integer but value displayed will be ‘M’ because the statement (char) converts integer to corresponding ASCII character.

cout <<“ y = “<<(int)y <<endl—The variable y is a float but before printing the value, 5.1252 is converted to integer and the output will be 5.

cout <<“ z = “<<(int)z—The variable z is of character type. The character value is converted to integer and the output displayed will be 65.

2.12 Write a program to display A to Z alphabets using ASCII values.

# include <iostream.h>
# include <conio.h>
# include <stdio.h>
main( ) 
 {
   clrscr( ); 
   int j;

   for (j=65;j<91;j++) 
   cout <<(char)j<<" "; 
   cout <<endl;

   for (j=65;j<91;j++) 
   printf ("%c ",j); 
   return 0;
 }

OUTPUT

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Explanation: In the above program, A to Z alphabets are displayed using cout( ) and printf( ) statements. In cout( ) statement, typecasting is done before printing. The integer is converted to corresponding char type symbol and displayed. In the printf( ) statement, the control string %c performs this task. The quotation mark (“ ” ) inserts space between two successive characters.

2.13 Write a program to display addresses of variables in hexadecimal and unsigned integer formats.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
  clrscr( );
   int x=77; 
   float y=5.1252;
   int z=78;

  cout <<" Address of x = "<<&x<<endl;  
  cout <<" Address of  y ="<<&y<<endl;
  cout <<" Address of z ="<<(unsigned)&z <<endl;
 } 

OUTPUT
Address of x = 0x887ffff4
Address of y = 0x887ffff0
Address of z = 65518

Explanation: The cout statement displays address of variables in hexadecimal format. The typecasting syntax (unsigned) converts hexadecimal to unsigned integer (decimal). The output shows addresses in both hexadecimal and unsigned integer (decimal) formats.

The & (ampersand) operator is used to display address of the variable. The address operator is preceded by the variable name. The address is always represented in unsigned integer. The cout statement displays the address in hexadecimal format. To convert the hexa-decimal address to unsigned integer, type casting is used.

2.14 Write a program to display string using different syntaxes using operator *, & with cout statement.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
  clrscr( );
   char *name="C Plus Plus";
   cout<<*&(name)<<"\n";
   cout <<&(*name)<<"\n";
   cout<<*&name<<"\n";
 }

OUTPUT
C Plus Plus
C Plus Plus
C Plus Plus

Explanation: In the first statement, the operator * and & are used one after another and the variable name is inside parenthesis. In the second statement, operator & is outside and operator * and variable name are inside the parenthesis. In the third statement there is no use of parenthesis. All the three statements display the output “C Plus Plus.”

DIFFERENCE IN USING C AND C++ I/O FUNCTIONS

The printf( ) and scanf( ) of C language need format string. For example, to read and display an integer the scanf( ) and printf( ) statements can be written as follows.

   int x;

   scanf(“%d”,&x)

   printf(“%d”,x);

In the above statements %d is used to tell the I/O functions to treat the data as integer.

If the integer x is changed to long integer the programmer needs to change every occurrence of %d in the program with %ld.

The C++ statement reads and displays the same data as follows.

   int x;

   cin>>x;

   cout<<x;

Here, the cin and cout statements do not require any format string. If the type of x is changed to long integer, the user won't need to specify the type of data or any correction in the statement. The cin and cout statement identifies the data type. The format of cin and cout statements is same for all types of variables.

   get( ) and put( ) functions

   get( ) function

The single character input and output operations in C++ can be done with the help of put( ) and get( ) functions. The class istream and ostream provides the two member functions put( ) and get( ). The get( ) is used to read a character and put( ) is used to display the character on the screen.

The get( ) function has two syntaxes.

(a) get(char*);

(b) get(void);

If syntax (a) is used, the get( ) function assigns the read data to its argument, whereas if syntax (b) is used, the get( ) function returns the data read. The data is assigned to the variable present at left-hand side of the assignment operator. These functions are members of I/O stream classes and can be called using object.

put( ) function

The put( ) function is used to display the string on the screen. It is a member of ostream class. The syntax of put( ) is given below.

(a) cout.put(‘A’);

(b) cout.put(x);

The statement (a) displays the character ‘A’ on the screen and the statement (b) displays the contents of variable x on the screen. If an integer is used as an argument, its corresponding ASCII value is displayed. Few examples, are illustrated below.

2.15 Write a program to display the character on the screen using put( ) function.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   clrscr( );
   cout.put(‘C’); 
   cout.put(‘+’); 
   cout.put(‘+’);
 }

OUTPUT
C++

Explanation: The cout.put( ) statement displays one character at a time on the screen. In this program three characters are displayed on the screen using cout.put( ) statement.

2.16 Write a program to use multiple put( ) statements with single cout object and display the characters.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   clrscr( );
   cout.put(‘C’).put(‘+’).put(‘+’);
 }

OUTPUT
C++

Explanation: In the above program, the single object cout is used followed by sequence of put( ) statement. The put( ) statements are separated by dot operators. In this way multiple statements can be combined.

2.17 Write a program to read character using get( ) and display it using put( ).

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   char ch; 
   clrscr( );
   cout <<"\n Enter a character : "; 
   cin.get(ch);
   cout <<"\n Entered character was : "; 
   cout.put(ch);
 }

OUTPUT
Enter a character : C

Entered character was : C

Explanation: In the above program, character variable ch is declared. The first cout statement displays message “Enter a character:” on the screen. The cin.get( ) function activates input stream and character entered by the user is stored in the variable ch. The cout.put( ) statement displays the character on the screen.

2.18 Write a program to read characters using sequence of get( ) statements and display read characters using sequence of put( ) statement.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   char ch[3]; 
   clrscr( );
   cout <<"\n Enter characters : "; 
   cin.get(ch[0]).get(ch[1]).get(ch[2]); 
   cout <<"\n Characters Entered : "; 
   cout.put(ch[0]).put(ch[1]).put(ch[2]);
}

OUTPUT
Enter characters : cpp
Characters Entered : cpp

Explanation: In the above program, a character array ch[3] is declared. The sequence of get( ) and put( ) functions are used to read and display the characters. The get( ) function reads characters and stores in array ch[3] . The put( ) function displays the same on the screen.

2.19 Write a program to read and display the string. Use get( ) and put( ) functions.

# include <iostream.h>
# include <conio.h>
# include <stdio.h>
main( )
 {
   clrscr( ); 
   char j=0; 
   char x[20];
   cout <<"\n Enter a string : ";

   while(x[j++]!=‘\n’) 
   cin.get(x[j]); 
   j=0;
   cout <<"\n Entered string : "; 
   while(x[j++]!=‘\n’) 
   cout.put(x[j]); 
   return 0 ;
 }

OUTPUT
Enter a string : Programming
Entered string : Programming

Explanation: In the above program, the character array x[] is declared. The first while loop reads characters using cin.get( ) function through the keyboard. When user presses enter key, the while loop terminates. The second while loop displays the characters read using function cout.put( ).

getline( ), read( ) and write( ) function

getline( )

The getline( ) and write( ) functions are useful in string input and output. The getline( ) function reads the string including white space. The cin ( ) function does not allow the string to enter with blank spaces. The input reading is terminated when user presses the enter key. The new line character is accepted but not saved and replaced with the null character. The object cin calls the function as follows.

cin.getline(variable, size);

where the variable name may be any character, array name and size is the size of the array.

read( ) : The read( ) function is also used to read text through the keyboard. The syntax of read is given below.

cin.read(variable, size);

where the variable name may be any character, array name and size is the size of the array.

When we use read statement it is necessary to enter character equal to the number of size specified. The getline( ) statement terminates the accepting data when enter is pressed where as the read( ) continues to read characters till the number of characters entered are equal to the size specified.

write( )

The write( ) function is used to display the string on the screen. Its format is the same as getline( ) but the function is exactly opposite. The syntax is given below.

cout.write (variable, size);

where variable name is a character type and size is the size of the character arrays. The cout. write ( ) statement displays only specified number of characters given in the second argument, though actual sting may be more in length. If the size of array is larger than the actual string length then the size argument contains the actual size of the array. In this case the getline( ) displays blank spaces for remaining unfilled elements. The following program illustrates both the functions:

2.20 Write a program to read characters using read( ) statement.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   char name[20];
   cout<<"\n Enter a string : "; 
   cin.read(name,20); 
   cout<<endl; 
   cout.write(name,20);
 }

OUTPUT
Enter a string : abcdefg
Hijkl
Mnopq

Abcdefg
Hijkl
Mnopq

Explanation: In the above program, the input data and output data can be seen in three lines. This is because when we enter data, enter keys are pressed. The same effect is produced while displaying the data. The enter key is stored as ‘\n’.

2.21 Write a program to display string using cout.write( ) statements.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.write ("INDIA",6); 
   cout.write ("IS",3); 
   cout.write ("GREAT",5);
 }

OUTPUT
INDIA IS GREAT

Explanation: In this program, the first statement displays “INDIA” followed by one blank space. This is because the argument value is greater by one than actual string length.

Similarly, the second statement displays “IS” followed by one blank space. The reason is same. The last statement displays “GREAT.” Here, the argument value and string lengths are same and no blank spaces are displayed.

In case the argument value is lesser than the actual string length, the complete string will not be displayed. The number of characters of the string displayed will be up to the given argument.

2.22 Write a program to show the effect if less argument is given than actual string length in the cout.write( ) statement.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.write ("SUNDAY",3);
 }

OUTPUT
SUN

Explanation: In the above program, the cout.write( ) will not display the complete string. The statement displays the characters according to the value of second argument. The value of second argument is three. Hence, instead of 6 characters only three characters are displayed and remaining characters are skipped.

2.23 Write a program to read string using getline( ) function and display it using write( ) statement.

# include <iostream.h>
# include <conio.h>
# include <string.h>
main( )
 {
   clrscr( ); 
   char x[30];
   cout <<"\n Enter any string : "; 
   cin.getline(x,30);
   cout <<"\n Entered string : " <<x;
   cout <<"\n Entered string : ";
   cout.write(x,30);
   cout <<"\n Entered string : ";
   cout.write(x,strlen(x));
   return 0 ;
 }

OUTPUT
Enter any string : C++ is advanced C
Entered string : C++ is advanced C
Entered string : C++ is advanced C h  > &
Entered string : C++ is advanced C

Explanation: In the above program, the x[] is a character array. The getline( ) function reads string through the keyboard. The getline( ) function accepts the string including spaces. The cout( ) statement displays the string including white spaces. The first write( ) statement displays the string with garbage values because the string length is less than the actual size of the array. In the second write( ) statement, strlen( ) function calculates the length of the string and length is used as an argument in the write( ) statement. This statement displays the entered string without any garbage collection.

The cin( ) statement cannot accept string including spaces. It accepts only single word. The cout( ) statement displays the string read through cin( ) and getline( ) functions i.e., it can display the string with and without blank spaces. The write( ) statement displays the string according to size specified. It displays the string with and without blank spaces. The write( ) does not support any escape sequence.

2.24 Write a program to display the string using different arguments in write( ) statement.

# include <iostream.h>
# include <conio.h>
# include <string.h>
main( ) 
 {
   clrscr( ); 
   char a,x[30];
   cout <<"\n Enter any string : ";
   cin.getline(x,30);
   cout <<"\n Entered string : \n";
   for(a=0;a<=strlen(x);a++) 
 {
   cout <<"\n"; 
   cout.write(x,a);
 }
   return 0 ; 
 }

OUTPUT
Enter any string : C Plus Plus

Entered string :

C
C
C P
C Pl
C Plu
C Plus
C Plus
C Plus P
C Plus Pl
C Plus Plu
C Plus Plus

Explanation: In the above program, a string is entered using getline( ) function. The for loop executes from 0 to the length of the string. The string length is calculated using strlen( ) function in the for loop. In each iteration value of loop, variable a is used as an argument in the write statement. The write statement displays the number of characters according to value of a.

2.25 Write a program to read two strings through the keyboard. Concatenate the strings and display the resulting string.

# include <iostream.h>
# include <conio.h>
# include <string.h>
main( ) 
 {
   clrscr( );
   char a[15], x[15] ;
   cout <<"\n Enter any string : ";
   cin.getline(a,15);
   cout <<"\n Enter any string : ";
   cin.getline (x,15);
   cout <<"\n The Concatenated strings : ";
   cout.write(a,strlen(a)) .write(" ", 1) .write(x,strlen(x));
   return 0 ;
 }

OUTPUT

Enter any string : Good

Enter any string : Morning

The Concatenated strings : Good Morning

Explanation: In the above program, two strings are entered in character arrays x[] and a[]. The successive write( ) statement in one line displays the string one after another. Thus, we can use multiple write( ) statements followed by single cout object.

2.9 MEMBER FUNCTIONS OF ISTREAM CLASS

The istream contains following functions that can be called using cin object.

peek( ): It returns the succeeding characters without extraction.

Example: cin.peek( )==‘#’;

where cin is an object and ‘#’ is a symbol to be caught in the stream.

ignore( ): The member function ignore( ) has two arguments, maximum number of characters to avoid, and the termination character.

Example: cin.ignore(1,‘#’);

The statement ignores 1 character till ‘#’ character is found.

2.26 Write a program to demonstrate the use of peek( ) and ignore( ) functions.

# include <iostream.h>
# include <conio.h>
main( ) 
 {
   char c; 
   clrscr( );
   cout <<"enter text (press F6 to end:) ";
   while(cin.get(c)) 
  {
   cout<<c;
   while(cin.peek( )==‘#’) 
  {
   cin.ignore(1,‘#’); 
  }
   }
   return 0; 
    }

OUTPUT
enter text (press F6 to end 🙂 ABCDEFG###HIJK^Z
ABCDEFGHIJK

Explanation: In the above program, the cin.get( ) function continuously reads characters through the keyboard till the user presses F6. The cout statement inside the loop displays the contents of variable c on the console. The cin.peek( ) statement checks the variable c. The variable c containing ‘#’ is ignored from the stream and not displayed on the screen.

putback ( ) The putback( ) replaces the given character into the input stream

Example: cin.putback (‘*’);

cin is an object and * is the symbol. The putback( ) function sends back the given symbol into input stream. It replaces the previous character with the new one specificed in the putback( ) function.

2.27 Write a program to demonstrate the use of putback( ) function.

# include <iostream.h>
# include <conio.h>
main( ) 
 {
   char c; 
   clrscr( );
   cout <<"enter text (press F6 to end : ";

   while (cin.get(c)) 
  {
   if (c==‘s’) 
   cin.putback(‘S’);
   cout.put(c); 
  }
return 0; 
}

OUTPUT
enter text (press F6 to end 🙂
c plus plus^Z
c plusS plusS

Explanation: In the above program, the cin.get( ) function continuously reads characters through the keyboard till the user presses F6. The cout statement inside the loop displays the contents of variable c on the console. The if statement checks the contents of variable c. If variable c contains small letter ‘s’, the putback( ) statement sends capital ‘S’ in the stream. The small ‘s’ is replaced with capital ‘S’. The contents displayed will be with capital ‘S’.

gcount( ): This function returns the number of unformatted characters extracted from input stream. The last statement should be get( ), getline( ), or read( ).

2.28 Write a program to demonstrate the use of gcount( ) function.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   char text[20];
   int len;
   clrscr( );
   cout <<"Enter text : ";
   cin.getline(text,20);
   len=cin.gcount( );
   cout<<"The Number of characters extracted are : "<<len;
 }

OUTPUT
Enter text : Virtual
The Number of characters extracted are : 8

Explanation: In the above program, the getline( ) function reads text through the keyboard. The gcount( ) function returns the number of characters extracted from stream to variable len. It also counts the null character. The cout statement displays value of variable len on the screen.

2.29 Write a program to perform the operation with peek( ) and putback( ).

# include <iostream.h>
# include <conio.h>
main( ) 
 {
   char c; 
   clrscr( );
   cout <<"enter text (press F6 to end :) ";
   while (cin.get(c)) 
  {
   if (c==‘  ’)
   cin.putback (‘.’); 
   else
   cout <<c;
   while (cin.peek( )==‘#’) cin.ignore(1,‘#’); 
  }
   return 0; 
 }

OUTPUT
Enter text (press F6 to end:) One! Two! Three! Four!
One..Two..Three..Four.
^Z

Explanation: In the above program, the cin.get( ) function reads data through the keyboard using first while loop. The if condition checks blank spaces in the entered text. If space is found, the putback( ) statement replaces space dot(.). The putback( ) sends the given character in the input stream. The peek( ) also checks the ‘#’ symbol in the entered text. If it is found ignore( ) statement ignores the character and the character won't be displayed on the screen. The program is terminated when key F6 or ctrl + z is pressed.

2.10 FORMATTED CONSOLE I/O OPERATIONS

C++ provides various formatted console I/O functions for formatting the output. They are of three types.

(1) ios class function and flags

(2) Manipulators

(3) User-defined output functions

The ios grants operations common to both input and output. The classes derived from ios are (istream, ostream, and iostream) special I/O with high-level formatting operations: The iostream class is automatically loaded in the program by the compiler. Figure 2.6 describes hierarchy of stream classes.

(a) istream performs formatted input.

(b) ostream performs formatted output.

(c) iostream performs formatted input and output.

The streambuf allows an abstraction for connecting to a physical device. Classes derived from it work with files, memory, etc. The ios communicates to a streambuf. It keeps information on the state of the streambuf(good, bad, eof, etc.), and saves flags for use by istream and ostream.

■ The streambuf class controls the buffer and its related member functions. It allows the ability to fill, flush, and empty the buffer.

■ The streambuf is an object of ios class. The base class of input and output stream classes is ios class.

■ The istream and ostream classes are derived classes of ios class and control input and output streams.

■ The iostream class is derived class of istream and ostream. It provides input and output functions to control console operations.

Table 2.3 describes the functions of ios class in brief. Figure 2.9 indicates various formatted output functions supported by cout object.

Table 2.3 ios class functions

Function Working
width( ) To set the required field width. The output will be displayed in given width.
precision( ) To set number of decimal point for a float value.
fill( ) To set a character to fill in the blank space of a field.
setf( ) To set various flags for formatting output.
unsetf( ) To remove the flag settting.

Fig.2.9 Formatted functions with cout object

(1) ios::width (member functions)

The width( ) function can be declared in two ways.

Declaration:

(a) int width( );

(b) int width(int);

(a) ios::width :

Declaration:

int width( );

If this function is declared as given above, it returns to the present width setting.

(b)ios::width

Declaration:

int width(int);

If this function is declared as given above, it sets the width as per the given integer, and returns the previous width setting. The setting should be reset for each input or output value if width other than the default is desired.

2.30 Write a program to set column width and display the characters at specified position.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout . width(5); 
   cout <<"A";
   cout . width(15); 
   cout <<"B";
 }

OUTPUT
A              B

Explanation: The first cout. width( ) statement sets the width 5. The cout statement sets the column width position at 5 and displays the character “A” at column 5. Similarly, the column width is set 15 and the character ‘B’ is displayed at the 15th column.

2.31 Write a program to use both the formats of width( ) function and display the result.

# include <iostream.h>
# include <conio.h>
void main( ) 
 {
   clrscr( ); 
   cout.width(50); 
   int x=cout.width(1); 
   cout <<x;
 }

OUTPUT

50

Explanation: In the above program, the width( ) function call sets the width at column 50. The second width( ) function call sets the width at column 1 and returns the previous setting i.e., 50. The integer x collects this value. The cout( ) statement displays the number 50 at column 1.

(2) ios::precision

This function can be declared in two ways.

Declaration:

(a) int precision(int);

(b) int precision( );

(a) int precision(int);

Declaration:

int precision(int);

If the function is declared as given above, it sets the floating-point precision and returns the previous setting. The precision should be reset for every value being output if we want a precision result other than the default.

(b) ios:: precision

Declaration:

int precision( );

If the function is used as given above, it returns the current setting of floating-point precision.

2.32 Write a program to set precision to two and display the float number.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.precision(2); 
   cout <<3.1452;
 }

OUTPUT
3.14

Explanation: In the above program, the cout.precision( ) statement sets float point precision to 2. The cout statement displays 3.14 instead of 3.1452.

2.33 Write a program to set a number of precision points. Display the results of 22/7 in different precision settings.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   int x=0; 
   float pi;
for (x=10;x>=1;x--) 
  {
   pi=(float)22/7; 
   cout.precision(x); 
   cout <<"\n"<<pi;
  }
   x=cout.precision(1);
   cout <<"\n\n Previous Setting :"<<x;
 }

OUTPUT
3.1428570747
3.142857075
3.14285707
3.1428571
3.142857
3.14286
3.1429
3.143
3.14
3.1
Previous Setting : 1

Explanation: In the above program, the for loop executes from 10 to 1 in reverse order. Each time in for loop, equation 22/7 is calculated and result is stored in the variable pi. The precision is set according to the value of variable x.

(3) ios::fill

This function can be declared in two ways.

Declaration:

(a) char fill( );

(b) char fill(char);

(a) ios::fill

Declaration:

char fill( );

If the function is used as above, it returns the current setting of fill character.

(b)ios::fill

Declaration:

char fill(char);

If the function is used as above it resets the fill character and returns the previous setting.

2.34 Write a program to set fill blank spaces with different symbols.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.fill(‘/’);
   cout.width(20);
   cout<<"WEL"<<endl;
   cout.fill(‘-’);
   cout.width(10);
   cout<<"DONE";
 }

OUTPUT

/////////////////WEL
---------DONE

Explanation: This program is same as the last one. Here two different characters are used to fill the blank spaces in the specified width. The width is specified using cout.width( ) statement. The output can be observed as shown below:

Tip: The character ‘\’ (back slash) is not allowed in cout.fill( ) statement to fill the blanks. This is because it is used with escape sequences.

2.35 Write a program to show the effect of cout.fill( ).

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   cout<<"Begin : "; 
   cout.width(15); 
   cout <<"ABC"; 
   cout<<"\n";
   cout<<"Begin : ";
   cout.width(15);
   cout.fill(‘#’);
   cout<<"ABC";
 }

OUTPUT :
Begin :               ABC
Begin : #######ABC

Explanation: In the first output line, blanks are displayed because the fill character is not set. In the second statement the symbol ‘#’ is displayed because the fill character is set to ‘#’. The output can be observed as shown below:

2.36 Write a program to fill the trailling digits of a number by ‘*’ symbol.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   int x=0,j=0; 
   float pi; 
   cout.fill(‘*’);
for (x=10;x>=1;x--) 
 {
   pi=(float)22/7; 
   cout.width(j++); 
   cout.precision(x); 
   cout <<"\n"<<pi;
 }
   cout.width(j++); 
   cout.precision(x); 
   cout <<"\n"<<pi; 
   x=cout.fill( );
   cout <<"\n\n Fill setting :"<<(char)x;
 }

OUTPUT

3.1428570747
3.142857075*
3.14285707**
3.1428571***
3.142857****
3.14286*****
31429******
3.143*******
3.14********
31*********
3.142857

Fill setting :*

Explanation: In the above program, the precision setting and display of floating point number using precision is the same as previous example. In the for loop each time width( ) is set to the value of variable j. The value of j increases at each iteration. The floating precision number decreases from top to bottom and blank spaces remain in the specified field area by the statement width( ). The unused area is filled with ‘*’. The setting of fill character is done before the for loop statement. The fill character may be set to any character. The fill( ) statement after for loop body displays the character used for filling.

(4) ios::setf

This function can be declared in two ways.

Declaration:

(a) long setf(long sb, long f );

(b) long setf(long);

(a) ios:: setf

Declaration:

long setf(long sb, long f);

The bits according to that marked in variable f are removed in the data member x_flags, and then reset to those marked in variable sb. Using the constants in the formatting flag enumeration of class ios can specify value of variable sb.

(b) ios:: setf

Declaration:

long setf(long);

If the above declaration is used in the program, it sets the flags according to those marked in the given long. The flags are set in the data member x_flags of class ios. The use of constants in the formatting flags can specify the long enumeration of class ios. It returns the previous settings.

2.11 BIT FIELDS

The ios class contains the setf( ) member function. The flag indicates the format design. The syntax of the unsetf( ) function is used to clear the flags. The syntaxes of function are as follows.

Syntax: cout.setf(v1, v2);

Syntax: cout.unsetf(v1);

where, variable v1 and v2 are two flags. Table 2.4 describes the flag and bit-field setting that can be used with this function. The unsetf( ) accepts setting of v1 and v2 arguments.

Table 2.4 Flags and Bits

    Format     Flag (v1)     Bit-field (v2)
Left justification ios::left ios:adjustfield
Right justification ios::right ios:adjustfield
Padding after sign and base ios::internal ios:adjustfield
Scientific notation ios::scientific ios::floatfield
Fixed point notation ios::fixed ios::floatfield
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
Hexadecimal base ios::hex ios::basefield

(a) ios:: adjustfield

It is a data member and used with setf( ) function to arrange padding to the left or right, or for internal fill. It can be declared as follows.

Declaration:

static const long adjustfield;

(b) ios::floatfield

It is a data member and used with setf( ) function to set the float point notation to scientific or fixed. It is declared as follows.

Declaration:

static const long floatfield;

(c) ios::basefield

It is a data member and used with setf( ) function to set the notation to a decimal octal, or hexadecimal base. It is declared as follows.

Declaration:

static const long basefield;

2.37 Write a program to display the message left and right justified.

# include <iostream.h>
# include <conio.h>

void main( )

 {
   clrscr( ); 
   cout.fill(‘=’);
   cout.setf(ios::right, ios::adjustfield);
   cout.width(20);
   cout <<"Figure " << "\n";
   cout.setf(ios::left, ios::adjustfield);
   cout.width(20);
   cout <<"Figure " << "\n";
 }

OUTPUT

=============Figure
Figure =============

Explanation: In the above program, the fill character is set to sign “=”. The setf( ) is set to right justified. The column width is set to 20. The message “Figure” appears at the 20th column. Before the message the blank space is filled with the sign “=”. Again the justification property is set to left in setf( ) function. The text appears left justified. The output can be observed as follows.

2.38 Write a program to display the number in scientific format with sign.

# include <iostream.h>
# include <conio.h>
 
void main( ) 
 {
   clrscr( ); 
   cout.fill(‘=’);
   cout.setf(ios::internal, ios::adjustfield); 
   cout.setf(ios::scientific, ios::floatfield); 
   cout.width(15); 
   cout <<- 3.121;
 }

OUTPUT
- ===== 3.121e+00

Explanation: In the above program, the fill character is set to sign “=”. The setf( ) properties are set to internal and scientific. The scientific properties display the number in scientific (e) format. The internal properties display the sign in spaces before blank. If the settings were removed the output would be as given below:

Effect of statement

cout.setf (ios::internal, ios::adjustfield);

The output without this statement would be

The property ios::fixed displays the float number without scientific format, though the number is big. If the floating-point number is more than 6, extras are ignored. This format displays floating point up to 6 only.

2.39 Write a program to convert decimal number to hexadecimal and octal format.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.setf(ios::hex, ios::basefield); 
   cout <<"\n Hexadecimal of 184 is : "<<184; 
   cout.setf(ios::oct, ios::basefield); 
   cout <<"\n Octal of 15 is        : "<<15;
   cout.setf(ios::dec, ios::basefield); 
   cout <<"\n Decimal of 0xfe is    : "<<0xfe;
 }

OUTPUT
Hexadecimal of 184 is : b8
Octal of 15 is                : 17
Decimal of 0xfe is       : 254

Explanation: In the above program, the properties of setf( ) function are set to ios::hex, ios:: oct and ios::dec. After these settings, the decimal number given in cout( ) statement will convert to its hexadecimal and octal equivalent respectively. The hexadecimal number 0xfe is converted to its decimal equivalent.

2.12 FLAGS WITHOUT BIT FIELD

The flags described in Table 2.5 have no corresponding bit fields. The programs on these functions are illustrated below:

Table 2.5 Flags without bit fields

Flag Working
ios :: showbase Use base indicator on output
ios :: showpos Display + preceding positive number
ios :: showpoint Show trailing decimal point and zeroes
ios :: skipus Skip white space on input
ios :: unitbuf Flush all streams after insertion
ios :: uppercase Use capital characters for scientific and hexadecimal values
ios :: stdio Adjust the stream with C standard Input and output
ios :: boolalpha Converts bool values to text (“true” or “false”)

2.40 Write a program to use various setting given in the table.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout.setf(ios::showpos); 
   cout <<1254;

   cout.setf(ios::showpoint); 
   cout <<"\n"<<1254.524;

   cout.setf(ios::hex,ios::basefield); 
   cout <<"\n"<<184; 
   cout.setf(ios::uppercase); 
   cout <<"\n"<<184;
 }

OUTPUT
+1254
+1254.524000
0xb8
0XB8

Explanation: In the above program, the setting ios::showpos displays the + sign before the number 1254. The setting ios::showpoint displays the trailing zeroes after the number 1254.524. The setting ios::hex converts the decimal number to hexadecimal. It uses small letters. The setting ios::uppercase displays the hexadecimal number in uppercase.

2.13 MANIPULATORS

The output formats can be controlled using manipulators. The header file iomanip.h has a set of functions. Effect of these manipulators is the same as ios class member functions. Every ios member function has two formats. One is used for setting and second format is used to know the previous setting. But the manipulator does not return to the previous setting. The manipulator can be used with cout( ) statement as given below.

cout <<m1 <<m2 <<v1;

Here m1 and m2 are two manipulators and v1 is any valid C++ variable.

Table 2.6 describes the most useful manipulators. The manipulator hex, dec, oct, ws, endl, and flush are defined in iostream.h. The manipulator setbase, width( ), fill( ) etc. that requires an argument are defined in iomanip.h.

Table 2.6 Pre-defined manipulators

Manipulator Function
setw( int n) The field width is fixed to n.
setbase Sets the base of the number system.
setprecision(int p) The precision point is fixed to p.
setfill( char f) The fill character is set to character stored in variable f.
setiosglags(long l) Format flag is set to 1.
resetiosflags(long l) Removes the flags indicated by 1.
endl Splits a new line.
skipws Omits white space on input.
noskipws Does not omit white space on input.
ends Adds null character to close an output string.
flush Flushes the buffer stream.
lock Locks the file associated with the file handle.
ws Used to omit the leading white spaces present before the first field.
hex, oct ,dec Displays the number in hexadecimal, octal, and decimal format.

2.41 Write a program to display formatted output using manipulators.

# include <iostream.h>
# include <iomanip.h>
# include <conio.h>

main( )
 {
   clrscr( );
   cout <<setw(10) <<"Hello"<<endl;
   cout <<setw(15) <<setprecision(2) <<2.5555;
   cout <<setiosflags(ios::hex);
   cout <<endl<<"Hexadecimal of 84 is : "<<84;
return 0; 
 }

OUTPUT

Hello
        2.56
Hexadecimal of 84 is : 54

Explanation: In the above program, the manipulator setw(10) sets the field width to 10. The message “hello” is displayed at column10. The endl inserts a new line. In the second cout( ) statement, the setprecision(2) manipulator sets the decimal point to 2. The number 2.5555 will be displayed as 2.56 at column 15. The manipulator setiosflag sets the hexadecimal setting for the display of number. The last cout( ) statement displays the equivalent hexadecimal of 84 i.e., 54.

2.42 Write a program to display the given decimal number in hexadecimal and octal format.

# include <iostream.h>
# include <conio.h>
# include <iomanip.h>

void main( ) 
 {
   clrscr( ); 
   int x=84;
   cout <<"\n Hexa-decimal Number : "<<hex<<x; 
   cout <<"\n Octal Number : "<<oct<<x;
 }

OUTPUT
Hexadecimal Number : 54
Octal Number : 124

Explanation: In the above program, the integer variable x is declared and initialized with 84. The first cout statement displays the decimal number to its equivalent hexadecinal number. The manipulator hex converts decimal number to its hexadecimal equivalent. The second cout statement converts decimal number to its equivalent octal number.

2.43 Write a program to read number in hexadecimal format using cin statement. Display the number in decimal format.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( ); 
   int x;
   cout <<"\n Enter Hexa-decimal Number : "; 
   cin >>hex>>x;
   cout <<"\n Decimal Number : "<<dec<<x;
 }

OUTPUT
Enter Hexadecimal Number : 31

Decimal Number     : 25

Explanation: In the above program, the cin statement reads a number in hex format. The cout statement displays its equivalent decimal number with the use of dec manipulator.

2.44 Write a program to demonstrate the use of endl manipulator.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   cout <<" Demo of endl "; 
   endl(cout);
   cout <<" It splits a line" ;
 }

OUTPUT
Demo of endl
It splits a line

Explanation: In the above program, endl manipulator is used to split the line. The two strings are displayed on two separate lines.

2.45 Write a program to demonstrate the use of flush( ) statement.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   char text[20]; 
   clrscr( );

   cout <<"Enter text : "; 
   cin.getline(text,20); 
   cout<<"Text Entered : "<<text; 
   flush(cout);
 }

OUTPUT
Enter text : Buffer
Text Entered : Buffer

Explanation: In the above program, the statement flush(cout) flushes the buffer. This statement can be used as cout<<flush.

2.14 USER-DEFINED MANIPULATORS

The programmer can also define his/her own manipulator according to the requirements of the program. The syntax for defining manipulator is given below:

ostream & m_name( ostream & o ) 
{
   statement1; 
   statement2; 
   return o;
}

The m_name is the name of the manipulator.

2.46 Write a program to create manipulator equivalent to ‘\t’. Use it in the program and format the output.

# include <iostream.h>
# include <iomanip.h>
# include <conio.h>

ostream & tab (ostream & o)
{
   o <<"\t";
   return o;
}

void main( )
{
   clrscr( );
   cout <<1<<tab<<2 <<tab<<3;
}

OUTPUT
1 2 3

Explanation: Figure 2.10 illustrates working of the program.

Fig.2.10 Working of tab manipulator

In the above program, tab named manipulator is defined. The definition of tab manipulator contains the escape sequence ‘\t’. Whenever we call the tab manipulator, the ‘\t’ is executed and we get the effect of tab.

2.47 Write a program to display message using manipulator.

# include <iostream.h>
# include <iomanip.h>
# include <conio.h>

ostream & N (ostream & o) 
{
   o <<"Negative Number"; 
   return o;
}

ostream & P (ostream & o)
{
   o <<"Positive Number"; 
   return o;
}

void main( )
 { 
   int x; 
   clrscr( );
   cout <<"\n Enter a Number : "; 
   cin >>x; 

   if (x<0)
   cout <<x <<" is " <<N; 
   else
   cout <<x <<" is " <<P;
 }

OUTPUT
Enter a Number : -15
-15 is Negative Number

Explanation: In the above program, two manipulators N and P are created. When called, N displays the message “Negative number” and P displays the message “Positive Number.”

2.15 MANIPULATOR WITH ONE PARAMETER

The prototype declared in the iomanip.h as described earlier allows us to define individual set of macros. The manipulator can be created without the use of int or long arguments.

2.48 Write a program with one parameter to display the string in the middle of the line.

# include <iostream.h>
# include <iomanip.h>
# include <string.h>
# include <conio.h>

ostream& fc (ostream& ost, int iw) 
 {
   for (int k=0;k<((75-iw)/2);k++) 
   ost <<" "; 
   return (ost);
 }

OMANIP (int) middle (int iw) 
 {
   return OMANIP (int) (fc,iw);
 }
   int main( ) 
 {
   clrscr( );
   char *m=" * Well come *"; 
   cout <<middle (strlen(m)) <<m; 
   return 0;
 }

OUTPUT
                    ** WEL COME **

Explanation: In the above program, middle is a user-defined parameterized manipulator. It receives a value strlen(m) i.e., string length. The header file IOMANIO.H defines a macro, OMANIO (int). It is expanded to class_OMANIP_int. Due to this the definition consists of a constructor and an overloaded ostream insertion operator. When middle( ) function is added into the stream, it invokes the constructor which generates and returns an OMANIP_int object. The fc( ) function is called by the object constructor.

2.16 MANIPULATORS WITH MULTIPLE PARAMETERS

In this type of manipulator, multiple arguments are passed on to the manipulator. The following program explains it.

2.49 Write a program to create manipulator with two arguments.

# include <iostream.h>
# include <conio.h>
# include <iomanip.h>
# include <math.h>

struct w_p 
 {
   int w; 
   int p;
 };

IOMANIPdeclare (w_p);

static ostream& ff(ostream& os, w_p w_p) 
 {
   os.width (w_p.w); 
   os.precision(w_p.p); 
   os.setf(ios::fixed); 
   return os;
 }

OMANIP (w_p) column (int w, int p) 
 {
   w_p w_p; 
   w_p.w=w; 
   w_p.p=p;
   return OMANIP (w_p) (ff,w_p);
}
int main ( ) 
{
   clrscr( ); 
   double n,sq,sqr;
   cout <<"number\t" <<"square\t" <<"\tsquare root\n"; 
   cout <<"===================================\n";
   n=1.0;
for (int j=1;j<16;j++) 
{
   sq=n*n;
   sqr=sqrt(n);
   cout.fill(‘0’);
   cout <<column(3,0)<<n <<"\t";
   cout <<column(7,1) <<sq <<"\t\t";
   cout <<column(7,6) <<sqr <<endl;
   n=n+1.0;
}
   return 0; 
}

OUTPUT

number square square root
=========== =========== ===========
001 0000001 0000001
002 0000004 1.414214
003 0000009 1.732051
004 0000016 0000002
005 0000025 2.236068
006 0000036 2.44949
007 0000049 2.645751
008 0000064 2.828427
009 0000081 0000003
010 0000100 3.162278
011 0000121 3.316625
012 0000144 3.464102
013 0000169 3.605551
014 0000196 3.741657
015 0000225 3.872983

Explanation: The above program is same as the previous one. The only difference is that here two parameters are used. The user-defined manipulator is assigned two integer values. The first argument decides the number of spaces and the second argument decides number of decimal places. After initializing the w_p structure, constructor is called. The constructor creates and returns a _OMANIP object.

2.17 CUSTOM BUILT I/O OBJECTS

(1) Creating Output Object

We have studied the objects cin and cout and their uses. It is also possible to declare objects equivalent to these objects. The object declaration is same as variable declaration. In object declaration, instead of data type, the class name is written followed by object names.

For example,

ostream print(1);

In the above example, print is an object of class ostream. The ostream handles the output functions. The parenthesis with value one calls the constructor. The details about objects and constructors are illustrated in successive chapters of this book.

The object print can be used in place of cout. It can also call the member functions such as put( ), write( ) etc. The following programs illustrate this concept.

2.50 Write a program to declare object of ostream class and display the text on the screen.

# include <iostream.h>
# include <conio.h>

void main( ) 
{
   clrscr( );
   char text[10]="Hello"; 
   ostream print(1); 
   print<<text;
}

OUTPUT
Hello

Explanation: In the above program, the character array text is initialized with string “Hello”. The print is an object of class ostream. The print uses the operator << and displays the contents of array text on the screen.

2.51 Write a program to call member function of ostream class using custom object.

# include <iostream.h>
# include <conio.h>

void main( ) 
 {
   clrscr( );
   ostream print(1);
   print.put(‘C’).put(‘P’).put(‘P’);
 }

OUTPUT
CPP

Explanation: In the above program, print is an object of class ostream. The ostream invokes the member function put( ) and displays the given character on the screen.

(2) Creating Input Object

The object equivalent to cin can be declared as follows.

istream_withassign in;

Here, the istream_withassign is a class, which provides assignment operator. The object in is an object of the istream_withassign class.

in=cin;

The operator associated with cin is assigned to object in. Now the object in can be used instead of cin. The following program illustrates this point.

2.52 Write a program to create object equivalent to cin and perform input operation.

# include <iostream.h>
# include <conio.h>
void main( )
{
   clrscr( ); 
   char text[20]; 
   istream_withassign in; 
   in=cin;
   cout<<"\n Enter text : ";
   in.getline(text,20);
   cout <<"\n The text entered : ";
   cout<<text;
}

OUTPUT

Enter text : BE HAPPY

The text entered : BE HAPPY

Explanation: In the above program, in is an object of class istream_withassign. The operator associated with cin is assigned to object in. The in object invokes the function getline( ) and reads text. The read text is displayed by the cout statement.

SUMMARY

(1) The input output function of C++ works with different physical devices. It also acts as interface between the user and the device.

(2) A stream is a series of bytes that acts as a source and destination for data. The source stream is called input stream and the destination stream is called output stream.

(3) The cin, cout, cerr and clog are predefined streams.

(4) The header file iostream.h must be include when we use cin and cout functions.

(5) The istream and ostream are derived classes from ios base class. Figure 2.6 displays all the derived classes.

(6) The formatting of output can be effectively done with member functions ofios class. The member function width( ), precision( ), fill( ) and setf( ) allows user to design and display the output in formatted form.

(7) Table 2.3 describes the list of functions without bit fields. These functions are also used for formatting the output.

(8) The putback( ) replaces the given character into the input stream. The member function ignore, ignores a number of given characters till it finds termination character.

(9) Manipulators also help the user in formatting of output. The programmer can also create his/ her own manipulators.

(10) The header file iomanip.h contains pre-defined manipulators. Table 2.6 describes these manipulators.

EXERCISES

[A] Answer the following questions.

(1) List the names of pre-defined streams with their 'C' equivalents?

(2) What are formatted and unformatted input/output functions?

(3) Distinguish between

(a) cin( ) and scanf( )

(b) cout( ) andprintf( )

(c) ios::fixed and cout.precision( )

(4) What are the uses of put( ) and get( ) functions?

(5) What is the use of getline( ) function? Which two arguments does it require?

(6) Describe bit fields required in setf( ) function.

(7) List the flags without bit fields with their working.

(8) What is the role of iostream.h and iomanip.h header files?

(9) Write the statement for concatenation of two strings using cout.write( ) statement.

(10) Describe the procedure for designing manipulator.

(11) What is the function of peek( ) and ignore( ) functions?

(12) What are single and multiple parameter manipulators?

(13) In which format the cout statement display the address of variable? How can it be converted to unsigned?

(14) In which situation the putback( ) function is useful?

(15) What is the use of ignore( ) function?

(16) What do you mean by formatted and unformatted data?

(17) Explain the procedure for creating custom input/output objects.

[B] Answer the following by selecting the appropriate option.

(1) The cin and cout functions require the header file to include

(a) iostream.h

(b) stdio.h

(c) iomanip.h

(d) none of the above

(2) The set.precision( ) is used to set

(a) decimal places

(b) number of digits

(c) field width

(d) none of the above

(3) To fill unused section of the field, the character is set by the function

(a) fill( )

(b) width( )

(c) precision( )

(d) none of the above

(4) The manipulator <<endl is equivalent to

(a) ‘\n

(b) ‘\t

(c) ‘\b

(d) none of the above

(5) This function accepts the string with blank spaces

(a) getline( )

(b) cin

(c) scanf ( )

(d) none of the above

(6) The streams is a

(a) flow of data

(b) flow of integers

(c) flow of statements

(d) none of the above

(7) The statement cin<<hex reads the data in

(a) hexadecimal format

(b) octal format

(c) binary format

(d) decimal format

(8) The gcount( ) function counts the

(a) extracted character

(b) inserted character

(c) both (a) and (b)

(d) none of the above

(9) The buffer is used to move data between

(a) input/output devices and computer

(b) input and output devices

(c) input devices to storage devices

(d) none of the above

(10) The buffer is a

(a) block of memory

(b) part of ram

(c) part of hard disk

(d) none of the above

[C] Attempt the following programs.

(1) Write a program to receive 5 float numbers. Display the number with 6 decimal places.

(2) Write a program to display the hexadecimal, octal equivalent of 85, 25 152, 251, and 458 numbers.

(3) Write a program to display decimal equivalent of hexadecimal numbers 0x52, 0x98, 0x101, 0x524, and 0x421.

(4) Write a program to read ten records of student with the information name, age, and date of birth and arrange the output in the following format. Fill the unused field with dot.

(5) Write a program to accept string using get ( ) function. Display the string using write ( ) and put ( ) function. Mention the difference between write ( ) and put ( ) functions.

(6) Write a program to design following manipulators:

Manipulator Name Function ( Escape sequence)
<<bkp (Backspace) \b’ or ‘\r
<<newl \n
<<bell \a
<<plus ‘+’(Displays + sign)
<<dollar $ (Displays $ sign)

(7) Write a program to receive item code, quantity, price and calculate the amount. Display the data in the following format.

Note:     (a) Sr.No. and Item code is left justified.
       (b) The price and amount is right justified.
       (c) Three-digit precision for amount field.

(8) Write a program to enter text up to 100 characters through the keyboard. Ignore symbols and replace them with*. Display dot in-between two words.

(9) Given x = 5, y = 8, z = 12. State the value of the variable on the left side of the following statements:

(a) a = x/y*z

(b) b = y/z*x

(c) c = z*y/z

(d) d = x*z/y

(e) d = (x/y)*z

(10) If p = 0.5, q = –2.0, r = 7.3, s = 10.4, m = 2, n = –3, find the values that will be stored as the result of the following expressions:

(a) x = 5.0* p + q – (r + s*3.0)

(b) y = 3.0*p + q + s*2

(c) z = p*s + q*r –s*q/5.0

(d) a = sqrt(4.0 – r + 9.0*q)

(11) Solve the following algebraic expressions:

(a) k = 4.5 log10 x + 2xy + x5

(b) j = (bx + x)/(bx – b)

(c) z = (x)2 + (x + 1)2 + (x + 2)2

(d) u = a*b/(c + d*g + k) + e

(12) Write a program to generate following outputs.

               

(13) Write a program to generate following output.

               

(14) Write a program to calculate simple interest and total amount. Input Principal amount, period, and rate of interest.

(15) Write a program to set width and display the integer number.

(16) Write a program to demonstrate use of showpos and showpoint flags.

(17) Write a program to display square and cube of number 1.5 to 16.5 in table format.

(18) Write a program to display octal and hexadecimal equivalent of decimal number ranging from 100 to 200.

[D] Find the output of the following programs.

(1)

cout.setf(ios::left, ios::adjustfield);
cout.fill(‘*’);
cout.precision(2);
cout.width(7);
cout<<345.54;
cout.width(8);
cout<<78;

(2)

cout.setf(ios::internal, ios::adjustfield); 
cout.fill(‘$’); 
cout.precision(4); 
cout.width(11); 
cout<<-543.453;

(3)

cout.setf(ios::showpos);
cout.setf(ios::showpoint);
cout.setf(ios::internal, ios::adjustfield);
cout.precision(4);
cout.width(12);
cout<<2342.34;

(4)

cout.precision(2);
cout<<4.57<<endl;
cout<<7.1453<<endl;
cout<<4.5132<<endl;
cout<<8.004<<endl;

(5)

cout.fill(‘$’);
cout.precision(4);
cout.setf(ios::internal, ios:: adjustfield);
cout.setf(ios::scientific, ios:: floatfield);
cout.width(13);
cout<<-78.47854;

(6)

cout fillC (‘= ’);
cout setf(ios:: internal, ios::adjustfield);
cout setf(ios:: scientific, ios::floatfield);
cout unsetf(ios ::scientific);
cout width(15);
cout <<- 3.121;

(7)

cout.width (7); 
cout<<123<56;

(8)

# include <iostream.h>
# include <conio.h>
void main ( )
{
clrscr( );
int i;
char name[]="OBJECT";
for (i=6;i>=0;i--)
{
cout.write(name,i); 
endl(cout);
}
}

(9)

# include <iostream.h>
# include <conio.h>
void main ( ) 
{
clrscr( ); 
char name[2 0];
cout<<"\n Enter a string : ";
cin.getline(name,0);
cout<<name;
}