Managing Console IO Operations
Managing Console IO Operations
2
I/O System in C++ (Cont…)
• C++ programmer should not use C I/O system due to two reasons :
• First I/O methods in C++ supports the concept of OOP but I/O method of C does not.
• Secondly I/O methods in C can not handle the user defined data types such as class
objects.
• C++ uses the concept of streams and stream classes to implement its I/O operation with
the console and disk files.
• A stream is a general name given to a flow of data. In C++ a stream is represented by an
object of a particular class. So far we’ve used the cin and cout stream objects. Different
streams are used to represent different kinds of data flow. For example, the ifstream
class represents data flow from input disk files.
4
C++ Stream Classes
⚫ The C++ I/O system contains a hierarchy of classes that are used to define various streams
to deal with both the console and disk files. These classes
are called stream classes.
6 04/29/19
Overloaded operators >> and<<
⚫ Objects cin and cout are used for input and output of data by using the overloading of
>> and << operators.
⚫ The >> operator is overloaded in the istream class and << is overloaded in the
ostream class.
⚫ The following are the formats for reading and displaying :
cin>>variable1>>variable2>>…………..>>variable n
cout <<item1<<item2<<…………<<item n
7
put() and get() functions
⚫ The classes istream and ostream define two member functions get(),put() respectively
to handle the single character input/output operations.
⚫ There are two types of get() functions.
⚫ Both get(char *) and get(void) prototype can be used to fetch a character including
the blank space,tab and newline character. The get(char *) version assigns the
input character to its argument
⚫ and the get(void) version returns the input character.
⚫ Since these functions are members of input/output Stream classes,these must be
invoked using appropriate objects.
8
put() and get() functions
#include<iostream>
using namespace std;
int main()
{
char c;
cin.get( c ); //get a character from the keyboard and assigns it to c
while( c!='\n')
{ cout<< c; //display the character on screen
cin.get( c ); //get another character
}
} The get(void) version is used as follows:
char c;
c= cin.get();
⚫ The value returned by the function get() is assigned to the variable c.
9
put() and get() functions
#include <iostream>
using namespace std;
int main()
{
int count=0;
char c;
cout<<”INPUT TEXT \n”;
cin.get( c );
while ( c !=’\n’ )
{ cout.put( c);
count++;
cin.get( c );
}
cout<< “\n Number of characters =” <<count <<”\n”;
return 0;
}
10
getline() and write() functions:
⚫ The getline() function reads a whole line of text that ends with a newline character.
This function can be invoked by using the object cin as follows:
cin.getline(line,size);
⚫ The reading is terminated as soon as either the newline character ‘\n’ is encountered or
size-1 characters are read(whichever occurs first).
⚫ The newline character is read but not saved. instead it is replaced by the null character.
⚫ For example consider the following code:
char name[20];
cin.getline(name,20);
11
getline() and write() functions:
Assume that we have given the following input through key board:
Bjarne Stroustrup<press Enter >
This input will be read correctly and assigned to the character array name.
Let us suppose the input is as follows:
Object Oriented Programming<press Enter>
In this case ,the input will be terminated after reading the following 19 characters
Object Oriented Pro
12
Reading Strings With getline()
int main() {
int size=20;
char city[20];
cout<<"enter city name: ";
cin>>city; // cin cannot read white spaces
cout<<"city name:"<<city<<"\n";
cin.ignore();
cout<<"enter city name again: ";
cin.getline(city,size);
cout<<"city name now:"<<city<<"\n";
cout<<"enter another city name: ";
cin.getline(city,size);
cout <<"New city name:"<<city<<"\n";
cin.get();
return 0; }
13
Reading Strings With getline()
output would be:
first run:
Second run :
14
write() function
⚫ The write() function displays an entire line and has the following form:
cout.write(line,size);
line represents the name of the string to be displayed
second argument size indicates the number of characters
• Write function does not stops displaying the characters automatically when the
null character is encountered.
• Eg. char *str="C++";
• cout.write(str,10);
• It will display C++ [7 garbage characters]
15
Displaying String With write()
#include <iostream>
#include<string>
using namespace std;
int main()
{ char * string1=”C++”;
char * string2 =”Programming”;
int m=strlen(string1);
int n =strlen(string2);
for (int i=1;i<n;i++)
{
cout.write(string2,i); cout<<”\n”;
}
for (i=n;i>0;i--)
{ cout.write(string2,i); cout<<”\n”;}
17
Formatting Console I/O Operations
⚫ C++ supports a number of features that could be used for formatting the output.These
features include:
1. ios class function and flags.
2. manipulators.
3. User-defined output functions.
18
Formatted Console I/O Operations
Manipuators Equivalent ios Task
function
setiosflags() setf() To specify format flags that can control the form of
output display(such as left-justification and
right-justification)
19
Defining Field Width:width()
⚫ The width() function is used to define the width of a field
necessary for the output of an item.As it is a member
function, object is required to invoke it like
⚫ cout.width(w); here w is the field width.
⚫ Example:
cout.width(5);
cout<<543<<12<<”\n”;
will produce the following output:
20
Defining Field Width:width()
#include <iostream> for(int i=0;i<4 ;i++)
using namespace std; {
int main() cout.width(5);
{ cout<<items[i];
int items[4] ={ 10,8,12,15}; cout.width(8);
int cost[4]={75,100,60,99}; cout<<cost[i];
cout.width(5); int value = items[i] * cost[i];
cout<<"Items"; cout.width(15);
cout.width(8); cout<<value<<"\n";
cout<<"Cost"; sum= sum + value;
cout.width(15); }
cout<<"Total Value"<<"\n"; cout<<"\n Grand total = ";
int sum=0; cout<<sum<<"\n";
return 0;
}
21
Setting Precision: precision():-
⚫ We can specify the number of digits to be displayed after the decimal point while
printing the floating point numbers.
⚫ This can be done by using the precision () member function as follows:
cout.precision(d); where d is the number of digits.
⚫ Eg:
cout.precision(4);
cout<<sqrt(2)<<”\n”;
cout<<3.14159<<”\n”; Note:Unlike the function width(),precision() retains the
setting in effect until it is reset.That is why we have
cout<<2.50032<<”\n”; declared only one statement for precision setting which is
will produce the following output: used by all the three outputs.
1.141 (truncated)
3.142 (rounded to nearest cent)
2.5 (no trailing zeros)
cout<<std::fixed; should be use if expected precision after decimal point is needed
22
FILLING AND PADDING :fill()
⚫ The unused portion of field width are filled with white spaces, by default. The fill()
function can be used to fill the unused positions by any desired character.It is used in
the following form:
cout.fill(ch);
Where ch represents the character which is used for filling the unused positions.
Example:
cout.fill(‘*’);
cout.width(10);
cout<<5250<<”\n”;
The output would be:
23
FILLING AND PADDING :fill()
#include<iostream>
using namespace std;
int main()
{ cout.fill(‘<’);
cout.precision(3);
for(int n=1;n<6;n++)
{
cout.width(5);
cout<<n;
cout.width(10);
cout<<1.0/float(n)<<”\n”;
if(n==3)
cout.fill(‘>’);
}
cout<<”\nPadding changed \n\n”;
cout.fill(‘#’); //fill() reset
cout.width(15);
cout.precision(5);
cout<<12.345678<<”\n”;
return 0;
}
24
FORMATTING FLAGS,Bit Fields and setf():-
⚫ The setf() a member function of the ios class, can provide answers left justified.The
setf() function can be used as follows:
⚫ cout.setf(arg1,arg2)
arg1- formatting flags defined in the class ios. The formatting flag specifies the
format action required for the output
arg2-known as bit field which specifies the group to which the formatting flag
belongs.
for example:
⚫ cout.setf(ios::left,ios::adjustfield);
⚫ cout.setf(ios::scientific,ios::floatfield);
⚫ Note that the first argument should be one of the group member of second argument.
25
FORMATTING FLAGS,Bit Fields and setf():-
26
FORMATTING FLAGS,Bit Fields and setf():-
⚫ Consider the following segment of code:
cout.fill(‘*’);
cout.setf(ios::left,ios::adjustfield);
cout.width(15);
cout<<”TABLE 1”<<”\n”;
⚫ This will produce the following output:
cout.fill(‘*’); cout.precision(3);
cout.setf(ios::internal,ios::adjustfield);
cout.setf(ios::scientific,ios::floatfield);
cout.width(15);
cout<<-12.34567<<”\n”;
Will produce the following output:
27
Managing Output with Manipulators:-
⚫ The header file iomanip provides a set of functions called manipulators which can be
used to manipulate the output format. They provide the same features as that of the ios
member functions and flags.
⚫ For example,two or more manipulators can be used as a chain in one statement as
follows
cout<<manip1<<manip2<<manip3<<item;
cout<<manip1<<item1<<manip2<<item2;
28
Managing Output with Manipulators:-
⚫ Examples of manipulators are given below:
cout<<setw(10)<<12345;
This statement prints the value 12345 right-justified in a field of 10 characters. The
output can be made left-justified by modifying the statement as follows:
⚫ cout<<setw(10)<<setiosflags(ios::left)<<12345;
⚫ One statement can be used to format output for two or more values.
⚫ For example, the statement
⚫ cout<<setw(5)<<setprecision(2)<<1.2345<<setw(10)<<setprecision(4)<<sqrt(2)<<set
w(15)<<setiosflags(ios::scientific)<<sqrt(3);
⚫ will print all the three values in one line with the field sizes of 5,10,15 respectively.
29
Display Trailing Zeros and Plus sign
⚫ If we print the number 10.75,25.00 and 15.50 using a field width of 8 position and
with two digit fixed precision what will be output
30
Display Trailing Zeros and Plus sign
⚫ setf() can be used for this purpose with single argument ios::showpoint
⚫ Example: cout.setf(ios::showpoint);//display trailing zeros
⚫ Similarly, plus sign can be printed before a positive number using following
statement:
⚫ cout.setf(ios::showpos);//Shows + sign
⚫ Example
cout.setf(ios::showpoint); cout.setf(ios::showpos);
cout.precision(3);
cout.setf(ios::fixed,ios::floatfield);
cout.setf(ios::internal,ios:: adjustfield);
cout.width(10); cout<<275.5<<endl;
31
Predict the Output
#include<bits/stdc++.h>
using namespace std;
int main()
{
double pi = 3.14159, npi = -3.14159;
cout << fixed << setprecision(0) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(1) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(2) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(3) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(4) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(5) << pi <<" "<<npi<<endl;
cout << fixed << setprecision(6) << pi <<" "<<npi<<endl;
}
32
Predict the Output
int main ()
{
int n = -77;
std::cout.width(6);
std::cout << std::internal << n << “\n”;
std::cout.width(6); std::cout << std::left << n << “\n”;
std::cout.width(6);
std::cout << std::right << n << “\n”;
return 0;
}
33
⚫Creating user user
Syntax for creating defined manipulators
defined manipulators in C++
⚫ ostream & manipulator_name(ostream & output_str)
{
//set of statements;
return output_str;
}
⚫ Example:
ostream & unit (ostream & output)
{
output<<“inches”;
return output;
}
The statement cout<<50<<unit; will print 50 inches
34
Example
Consider the following example which creates a user defined manipulator
named curr for displaying Rs. and sets the precision to 2.
#include <iostream>
using namespace std;
#include <iomanip>
ostream & curr(ostream & ostr)
{
ostr<< setprecision(2);
ostr<<"Rs." ;
return ostr;
}
int main()
{
float amt = 4.5476;
cout<<curr<<amt;
return 0;
}
35
Output?
cout.precision(2);
cout<<3.555<<endl;
int p=cout.precision(4);//returns the last precision value
cout<<3.555<<endl;
cout.precision(p);
cout<<3.555;
Output:
3.5
3.555
3.5
36