Sunteți pe pagina 1din 26

CHAPTER FOUR from a program to a destination are called output

INPUT AND OUTPUT IN C++ streams.

Introduction A stream may not only contain a single data at a certain


Most C++ program applications involve three basic instance. A sequence of characters corresponding to a
stages: input, analysis and output. In the previous number of data may be temporarily lined up in a stream.
chapters, all these stages were included in the programs In such cases, the data in the stream is said to be buffered
we wrote. We used several input as well as output data.
statements to read data into our program and to display
You may raise an interesting question here. How do the
results on the screen. However, no emphasis was given
sequence of characters in the streams interact with a
on the way how data input or output took place. This
program? Let me ask you a question before we answer
chapter is devoted to analyze how input and output
this. In almost all of the programs we wrote, we included
processes take place in a C++ program and how the data
the <iostream> header file. Why do you think we did
can be formatted and manipulated.
that? It is because files like <iostream> have functions
Input and output of data can take place from the default which interact with streams. These functions interpret the
devices. The default input device is the keyboard while the sequence of characters in the streams and convey it to the
default output device is the screen. Besides, the input and appropriate variable in a program or the other way round.
output of data can also take place from other sources or Therefore, streams interact with programs through pre-
destinations such as files. In this chapter, input and output defined functions. The flow of data from a keyboard to a
procedures to both default devices and files will be program and from program to screen is pictorially
discussed. Whichever the source or destination is, the represented below.
input output in C++ is based on a concept known as
stream. Discussing about streams is vital for detailed
understanding of how input and output data can be
formatted and manipulated. Therefore, streams will be the
first topic in this chapter. Stay tuned till the end of the
chapter and you will love what we are going to discuss.
C++ Streams
What comes to your mind when you think of the word
streams? A flow of water, right? Good imagination. Now
think of two places in which water flows from the first to
the second delivering goods in its direction of flow.
Streams in C++ are just like the flow of water between The <iostream> file contains entities called classes
the two points. They deliver data from input source to that contain functions which interact with the input
your program or from your program to the destination. stream and output streams. The class which contains
In a water flow, it is the water which delivers goods. In functions which interact with input stream is called
C++ streams, it is the sequence of bytes which delivers istream. The class which contains functions which
the data. The sequence of bytes can be in a text or a binary interact with output stream is called ostream. In
form. However, most C++ applications use the text form addition, the <iostream> file contains a class called
of bytes which are characters. In short, streams are ios. This class contains some of the variables and
interfaces through which sequence of characters is operations for both input and output (I/O) operations.
transferred from a source to a destination.
To get access to the operations and functions in the
A typical program reads data and displays the result. If so, istream or ostream class, you need objects of the
how many type of streams do we normally need to write classes. The objects are like blue prints of the class which
a program? Two, right? One of the streams conveys data have the privilege to access the accessible members of the
from an input source such as keyboard to the program. class. For example cin is an object of istream and
The other stream conveys from your program to output cout is an object of ostream. The objects cin and
destination such as screen. Those streams through which cout are built-in streams for input and output operations
data is conveyed from input source to a program are respectively.
called input streams while the streams conveying data
When a C++ program begins execution, four built-in
streams will be opened automatically. These streams are
By: Asaye Chemeda Email: asayechemeda@yahoo.com 46
cin, cout, cerr and clog. The cin and cout are Rule 1: During extraction, any preceding white spaces
standard input and output streams respectively. Whereas and new lines before any of the variables are
the cerr and clog are output streams for standard skipped.
error output and buffered error output respectively. Rule 2: Extraction takes place until a white space or an
input with a different data type than the data type
Some of the functions in istream or ostream classes with which the variable is declared is
are invoked through the member access operator while encountered.
others are invoked with different operators. The member Rule 3: When an extractor encounters a different data
access operator is a dot (.) while the other operators are type than the variable for which it is going to
the extractors (>>) and inserters (<<). extract value from the input stream without
The relevant functions in the <iostream> file will be extracting any value prior to the encounter, the
discussed next. Note that, whenever we want to use program will be in fail state and any further input
operations and functions in istream , ostream or operations in the program will be aborted.
ios classes, the file <iostream> should be included Rule 4: When an extractor encounters an input with a
different data type than the variable for which it
in our program.
is going to extract value from the input stream
The inserter functions after some extraction was made, the extraction
The inserter functions are overloaded functions which will be terminated and the variable will be
insert data obtained from the program into the output assigned with extracted value before the
stream through the insertion operator (<<). This encounter. The rest data will be held in the input
operator is a binary operator which takes two operands. stream waiting for the next input operation.
On the left side, it takes ostream class objects, i.e. Rule 5: After completing the extraction, an extractor
output streams, such as cout and on the right hand side function leaves a white space.
it takes variables of designated data type. The extractor
What did you feel when you read the above rules? Same
functions are overloaded so that any type of ostream
old same old? Or interesting? Anyways, we will see how
object and any data type can be used as operands. The
the above rules may resolve some tricky problems in
inserter functions are also overloaded to insert any
programs. Dont you feel it is high time to write a program
number of variables into a single output stream.
to have a look at the implementation of the above rules?
The general form of inserter functions is as follows: Let us write one then. Note that, we are not going to write
a complicated program for this. It is the data which we
input which will make us realize how the above rules are
The extractor functions applied.
The extractor functions are overloaded functions which Program 4.1[Correct].cpp
extract data from the input stream and pass it to the
program through the extraction operator (>>). This
operator is a binary operator which takes two operands.
On the left side, it takes istream class objects, i.e. input
streams, such as cin and on the right hand side it takes
variables of designated data type. The extractor functions
are overloaded so that any type of istream object and
any data type can be used as operands. The general form
of extractor functions is as follows:

As shown in the above syntax, the extractor functions are


also overloaded to extract any number and data type of
variables with a single istream object.
Some of the rules to be followed for the extractor
operator are given below.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 47


The above program is simple, right? Two int variables x A continuous combination of characters were entered on
and y, one double variable z, one character variable c Input line 1. Since the first variable in the cin
and one string variable s are declared. All the variables statement on line 11 is an integer, the extraction
except s were read with overloaded extraction operator continued until a value with another data type, i.e.,
on line 11. Then the string variable is read on line 13. On character H, is encountered. (Rule 4). The integer value
the subsequent lines, the entered values are printed. As we before the character, 13, is extracted and assigned to the
said, it is not the program which matters. It is the data we value of x and the rest values will be held for another
enter. Now, let us see what the output will be for different input operation. Note that, had there been no integer
input data. before the character H, the program would be in fail state.
First run, The next input operation is an extraction which attempts
to assign a character variable c. Since any entered
character corresponding to the ASCII list of characters
can be considered as a char data type, the first character
in the held values, i.e., H will be extracted as a value of c.
Since a char variable only takes one character, the set of
characters after H will be held in the input stream.
Even if there were white spaces before the first input (10)
and the last input (12.76) on Input line 1, the The next extraction will attempt to extract the left over in
the input stream and assign to the next variable which is
values of x and z are 10 and 12.76 respectively.
an integer. Since the next integer until a non-integer
Because any preceding white spaces before the input data
character is encountered is 2091, this value will be
were skipped (Rule 1).
extracted as a value of y. Again, the rest values will be
Even if the string input on Input line 2 is C++ held in the input stream and the extractor attempts to
is fun!, only the string C++ is assigned for s. This extract them to a double variable. Since the dot character
is because, extraction took place only until a white space is part of a floating point value and since the other held
was encountered. (Rule 2). Note that, the input stream values are numbers, all the remaining values will be
still contains the string is fun! which is a left over extracted to z. Note that, the dot character is not part of
from the extraction on line 13. an integer data type. If the extractor finds the dot
character for the first time and has to assign the values
Second run, after the dot to an int data type variable, the program will
become in fail state.
The white spaces preceding the string in the Input
line 2 were skipped and only the string before another
encounter of a white space, i.e., Object-Oriented
was assigned to the string variable s. The string after the
While the first variable to be extracted is supposed to be white space, Programming will be held in the input
an integer, a character B is the first input entered on stream.
Input line 1. When the first extraction operation
encounters this and fails to extract the right value for the The way how Rule 5 works is best elaborated with other
int variable x, the program will be in fail state. All the istream class functions and its discussion will be put
extractions after the encounter and any further input off until we discuss those functions.
operations were aborted. (Rule 3). No matter what values What did you observe as strong sides of the insertion and
were extracted after this, we will not get the results which extraction operators? Definitely, it is their flexibility to
we expect. The displayed results also signify this. handle various forms of data. Do you agree? I hope you
Third run, do. The inserters and extractors are overloaded functions
and we have seen that they are very flexible in inserting or
extracting any of the basic data types in addition to string
variables. Besides, they can handle as many data as
possible for a single input or output stream.
Despite the above strong sides of them, however, we have
also noted some of the shortcomings of the extractors.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 48
Could you guess the main drawback of the extractors? It The get function given in Form 2 extracts a maximum
is the way they handle white spaces. They simply skip of number-1 characters from the input stream and
them and ignore any data after white spaces. However, assigns the extracted characters to characterArray
white spaces may be part of the data and the data after which will be null-terminated by the function. The
white spaces may be part of the data too. In such cases, extraction will also be terminated when a new line
where white spaces or the data after them are important, character is encountered. The encountered new line will
the istream and ostream classes have rich set of not be removed from the input stream.
functions. These functions will be discussed in the
subsequent topics. The get function given in Form 3 extracts a maximum
of number-1 characters from the input stream and
The put and get functions assigns the extracted characters to characterArray
The put and get functions are members of the which will be null-terminated by the function. The
ostream and istream classes. The put function is extraction will also be terminated when a new line
used to convey a single character at a time to the output character or a character the same as delimiter is
stream whereas the get function extracts a single encountered. The encountered new line or delimiter
character at a time from the input stream to a program. will not be removed from the input stream.
Note that, the characters may also include white spaces,
tab and new line characters. Both functions are invoked The get function given in Form 4 with empty
by applying the member access operator on the output or parameters extracts the next character in the input stream.
input streams. The return value of the function can be assigned to a
character variable.
The general form of the put function is given below.
When a program reaches statements like the above get forms, it
extracts one or more characters from the input stream, if there is any,
until the condition for terminating the extraction is filfilled.
The above statement will send a char data type
Otherwise, the program waits until a user enters a value.
characterVariable into the output stream. Note
that, the argument of put function can be a char data The following two statements assign the character
type variable, a character literal or an integer variable cVar with the next character in the cin stream.
corresponding to the equivalent ASCII value for a
character. For instance, the following three cout
statements display the character A on the output device.
Even if the above get form and put functions only
hand one character at a time, suitable loops can be used
to navigate through a large number of characters.
The following statement extracts characters until new line
The statement on Line 2 inserts the value of the cVar character is encountered or a maximum of 99 characters
variable to the output stream. The statement on Line 3 are extracted and assigns the characters to cArray. By
delivers the character A to the output stream. The the process, cArray will be null-terminated.
statement on Line 4 delivers the character with ASCII
number of 65.
The get function has many forms. The frequently used The following statement extracts characters until new line
ones are the following: character is encountered or a dot is encountered or a
maximum of 19 characters are extracted and assigns the
characters to cArray. By the process, cArray will be
null-terminated.

Let us see the implementation of these functions in a


program.
The syntax given in Form 1 extracts a char variable
from the input stream and assigns the value to
characterVariable.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 49
Program 4.2[Correct].cpp by the cin.get(c) statement on line 14 and the
program will not wait for us to enter a character.
Reading and writing any characters including white
spaces, tab and newline characters were the strong sides
of put and get functions. Did you notice that they have
major drawbacks too? It is obvious, the main drawbacks
of the put and get functions are the fact that they can
only handle one character at a time and that they only
interact with character variables. The first drawback can
be solved if there are functions which read or write a
number of characters at a time. Such functions are
discussed next.
The getline,read and write functions
These functions are members of the istream and
In the above program, a character variable c and a string ostream class which read or write one or more
variable str were defined on lines 6 and 7. The string characters in a single line. The getline function is
variable is read with an extraction operator on line 9. If invoked by input streams while the write function is
the data which we entered for str contains internal white
invoked by output streams with a member access
spaces, any characters after the first internal white space operator.
will be held in the input stream. (Rule 2 of extraction
operator). The next input operation will then start The getline function extracts characters from the
extracting the left overs. Since the next input operation is input stream and assigns them to a character array variable
the cin statement on line 14, the held characters will be or a string variable. When the extracted characters are
extracted by the get function one by one until a new line assigned to a character array variable, the null character is
character is encountered. The continuation of the automatically appended to the character array. The
extraction until new line character encounter is because getline function may have one of the following three
the criteria for the termination of the do-while loop is so. forms:
Now, let us enter C++ is fun! as an input. The set
of characters until the first white space, i.e., C++ will be
assigned to str variable. Each of the rest characters, i.e.,
is fun! will be extracted by the cin.get(c)
statement and printed by the cin.put(c) in the do-
The statement in Form 1 is used to extract characters
while loop. The output when the above string is entered
looks like: from istreamObject and assign the characters to the
characterArray. The rules for the extraction are:
Rule 1: The extraction continues until number-1
characters are read or new line character is
encountered whichever comes first.
Rule 2: If a new line character is encountered before
reading number-1 characters, the extracted
By the way, what do you think will happen if we enter a characters will be assigned to the
characterArray.
string with no spaces? All the characters in the string will
Rule 3: If there are more than number-1 characters in
be assigned to the str variable, right? The interesting
the input stream and the newline character is not
question is: what will be read by the cin statement on yet encountered, the program will become in fail
line 14 if all the characters are assigned to str? Will the state.
program wait until we enter a value? If you answer this Rule 4: Null character is automatically appended at the
correctly, it means that you have remembered Rule 5 of end of the characters.
the extractor function. Even if a string with no white
The statement in Form 2 is used to extract characters
space is entered, the extraction operator leaves a white
from istreamObject and assign the characters to the
space after it extracts. That white space will be extracted
characterArray. The rules for the extraction are:

By: Asaye Chemeda Email: asayechemeda@yahoo.com 50


Rule 1: The extraction continues until number-1 write function is given for the cout output stream as
characters are read or a character the same as follows:
delimiter is encountered or new line
character is encountered whichever comes first.
Rule 2: If a new line character is not encountered before
reading number-1 characters, and if a character We havent yet looked into any specific statements for
the same as delimiter is encountered, the C++ programs using the getline and write
extracted characters before the delimiter functions. Once we know how they are invoked and what
will be assigned to the characterArray. arguments they take, it is not that difficult to write few
The delimiter is extracted from the input stream statements though. The following program shows the
but it will not be included in the characters implementation of the functions in a program. Recalling
assigned to the characterArray. about how dynamic arrays are created might be necessary
Rule 3: If a new line character is encountered before for complete understanding of the program.
reading number-1 characters, and a character
the same as delimiter is not yet encountered, Program 4.3[getline skipped].cpp
the program will become in fail state.
Rule 4: If there are more than number-1 characters in
the input stream and the newline character or the
delimiter is not yet encountered, the
program will become in fail state.
Rule 5: Null character is automatically appended at the
end. However, if a character the same as the
delimiter is encountered, a white space but not a
null character is appended.
The statement in Form 3 is used to extract characters
from istreamObject and assign the characters to the
stringVariable. The extraction continues until new
line character is encountered.
The read function extracts characters arrays from an
invoking input stream. The general form of the read
function is:

In the above program, an int variable len, a character


In the above statement, the read function extracts
array c and a string pointer p were declared on lines 6, 7
length number of characters from
and 8 respectively. The variable len will be used to store
istreamObject and assigns to characterArray.
the size of a dynamic string array which is going to be
The extraction continues until length number of
created. The pointer p will be used to create the one-
characters are extracted.
dimensional dynamic string array with a size of len. On
The write function inserts characters arrays to an line 9, the user is prompted to enter the length of the
invoking output stream. The general form of the write string array, i.e. the value of len. This value is read with
function is: the extraction operator from the cin stream on line 10.
Due to the statement on line 11, a dynamic memory for
len number of string variables will be allocated at run-
In the above statement, the write function inserts time and the base address will be passed to the pointer p.
length number of characters from The user is prompted to enter len number of strings on
characterArray into ostreamObject. The line 12. The for-loop from line 13 through line 15 extracts
insertion continues until length number of characters a line of string from the cin stream and assigns to each
are inserted even if a null character is encountered. A row of the dynamic array. The for-loop between line 17
number of write functions can be concatenated on a and 19 will display these strings using the insertion
single output stream. The concatenated form of the operator.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 51


On line 20, the user is again prompted to enter a character Recalling Rule 5 of the extractor function will solve the
array. By the statement on line 21, a maximum of 9 mystery. The rule says the extractor operator (>>) leaves
characters will be extracted from the cin stream by the a white space after extracting in the input stream. Now,
first form of the getline function and will be stored let us look at line 10 of the program. The extractor
into the character array c. Two concatenated write operation is used to extract the value of len from the
functions on line 22 will insert 7 characters from the string cin stream. Which means that according to the rule,
Output: and 9 characters from the c into the cout there white space is still there in the cin stream after the
stream. statement on line 10.
On line 23, the user is prompted to enter a character array During the first loop of the for-loop between lines 13 and
with a comma. The comma will be used as a 15, the getline function on line 14 gets this white
delimiter. On line 24, the second form of the space in the cin stream and the newline character after
getline is invoked by cin to extract a maximum of 9 that. As a result, the getline function will not make
characters from the invoking stream and assign it to c. if the program wait for us to enter a character during the
the line of characters contain a comma within the first 9 first loop. It already assigned the white space in the cin
characters, the extraction will be terminated. Another stream as the first row of the dynamic array. What
concatenated write function similar to the one on line happened after this? Only two loops were remaining and
22 is used to insert the new value of c to cout stream so the program waited for us to enter only two strings for
that it will be displayed on the screen. the second and third rows of the dynamic array. Now,
look at the output. There is a white space between the
Now, let us run the program and enter the required data phrase The printed strings are: generated
and analyze the output. Here is an output from a sample by line 16 of the program and the print of the first string
run. we entered. This white space is the first row of the
dynamic array.
After this, the program prompted us to enter a character
array to be extracted by another form of getline
function on line 21. Since the maximum number of
characters which this getline function call extracts is
9 (=10-1), we entered the string Iostream which
has 8 characters. Note that entering more than 9
characters would have resulted in the program to be in fail
state. This string was inserted into the cout stream by
the write function on line 22 and exactly what we
entered was printed.
By the statement on line 23, we were prompted to enter a
In the above sample run, the length of the string or the character array with a comma. We entered the string
value of len is entered to be 3. After this, the program ios,istream,ostream. This string was
prompted us to enter 3 strings. Let us enter Input extracted by the getline function on line 24. This
stream as the first string, Output stream as the getline function extracts a maximum of only 9
second string. But when we were ready to enter the third characters or until it encounters comma. In the string we
string, the program did not let us. It just printed the two entered, comma appeared as a fourth character.
strings which were entered. The value of len is 3 and we Therefore, it extracts only the first three characters, i.e.,
expected the program to wait for us until we enter 3 ios and it assigns them to the character array c. By
strings; each followed by pressing the Enter key which Rule 5 of getline function, when a delimiter is
creates a new line character. But, why did the program not encountered before extracting all the characters, a white
let us to enter the third string? Is there anything wrong space without a null character is appended to the
with the for-loop? Did we make it loop only two times? extracted string. Note that, the character array c was
No. It loops three times. Did we introduce a newline already assigned with 8 characters and a null character was
character in the middle of the strings we entered and the appended by the statement on line 21 and by the
getline function picked two strings within a single Iostream string we entered. After the getline
loop? No. We introduced the new line character only at function on line 24, however, the first three characters in
the end of the strings we entered. What is going on then?
By: Asaye Chemeda Email: asayechemeda@yahoo.com 52
c were replaced by the characters i, o and s In the syntax given by Form 1, the ignore function
respectively and the fourth character was replaced by a discards number characters from the
white space appended to these characters. Which means istreamObject. The ignore function syntax given
that the first four characters extracted by the getline by Form 2 discards a maximum of number characters
function on line 21 were replaced with the four characters from the istreamObject if delimiter is not
extracted by the getline function on line 24. Since null encountered. If a delimiter is encountered before
character is not appended to the characters extracted by discarding number characters, the discarding will be
the getline function on line 24, the unreplaced terminated after the delimiter is removed from the
characters in c still exist. Therefore, when c is printed by input stream.
the write function on line 25, the displayed string is
ios ream. The default value for number is 1 and we can omit
passing the value of number as an argument; in which
By the way, we have solved the mystery why the case, the function assumes its value to be equal to 1.
getline function in the for-loop between lines 13 and
15 is not waiting for the same number as the value of len Let us consider the following piece of code.
we enter. Can you give any suggestion how this could be
improved? One of the ways to make the getline
function inside the for-loop wait for the same number as
the value of len is to extract the white space left in the
input stream before the for-loop is entered. One of the
ways to do this is to use the get function. For instance, In the above piece of code, a character array c with a size
including the following statement anywhere between the of 100 is declared on Line 1. The statement on Line 2
cin statement on line 10, where the white space is makes the program wait until the user enters a character
produced, and the first for-loop will solve the problem. and discards 5 of them. If fewer than 5 characters are
entered, the program still waits for an input. The
ignore function also discards the newline character
which is produced by pressing the Enter key. After
Recall that we used the same approach in Program 3.8 in discarding 5 characters the program will proceed to
chapter three. On line 10 of program 3.8, we introduced executing the next line.
the above statement to extract a white space left from an
extraction operator. The statement on Line 3 discards a maximum 10
characters or all the characters before the delimiter , is
There are also other ways by which unwanted characters encountered, whichever comes first, from the cin
such as the white space produced by the extraction stream. If the delimiting character is not encountered nor
operator in Program 4.3, can be excluded from a string. 10 characters are not yet removed, the program waits for
The above option by using the get function only removes other characters to be entered.
only one unwanted character at a time. In addition, it is
not an ultimate way of removing unwanted characters After 5 characters are discarded by the statement on Line
from a string. C++ provides with another function by 2 and 10 or the characters before , are removed by the
which any number of unwanted characters can be ignore function on Line 3, what is left in the cin
removed from an input stream. This function is the next stream will be extracted by the getline function on
topic to be discussed. Line 4. If there is no any character in cin by then, the
program will wait for other characters to be entered.
The ignore function
Another member of the istream class, ignore, By the way, the ignore function is the best candidate to
discards specified number of characters or the characters solve the problem which we faced in Program 4.3, by
before a delimiting character is encountered from the discarding the unnecessary white space produced by the
invoking stream. The function is overloaded to have the extraction operator. Since the default value for number of
following two formal parameter types. characters to be discarded is one, the following statement
could also be used to discard the unnecessary white space.

So far, we have learned a number of functions which are


used to interact with the input and output streams. Didnt
By: Asaye Chemeda Email: asayechemeda@yahoo.com 53
they widen the options which we have to control what is The peek statement on Line 3 reads the first character
passed to the program from the input stream and what is within the cin stream, which is the same as c1, and
delivered to the output stream? Definitely yes. The returns the value for a new character variable, c2. Note
functions which we learned are not the only ones and that the peek function doesnt remove the character
there are plenty. Are you interested in learning few more? from cin. It just returns its value.
I hope you are. Let us discuss the next ones then.
The cin.get() on Line 4 then extracts the first
Have you noticed that all the functions which we character from cin and assigns it to a new character c3.
discussed so far always removed the characters which they The statement on Line 4 doesnt make the program wait
handled from the input stream? What if we want to for a character to be entered. Because there is already a
operate on a character without removing it from the input character in the input function. The character which is
stream? What if we want to put back characters into the extracted from cin by the get function on Line 4 is the
input stream? Does C++ answers for this question too? same character which was put back by the statement on
Of course, it does. The next topic will show us how. Line 2 and which was copied by the peek function on
The putback and peek functions line 3. Therefore, after Line 4, the value of the characters
These functions are members of the istream class. c1, c2 and c3 will be the same as the value which was
Both functions can only handle one character at a time. entered on Line 1.
The putback function puts back a character literal or Some of the functions which interact with the input
the value of any character variable into the invoking input stream may result in a program in fail state if inappropriate
stream. Whereas the peek function returns the value of data is entered. For instance, if the extraction operator
the first character in the invoking stream without encounters a different data type than what it expects and
removing the character from the stream. if it cant have other options to bypass the inappropriate
The syntax for the putback function is: data, the program will become in fail state. The
getline function can also lead to a program in fail state
if more characters than what it expects is introduced into
the input stream. Do you remember what the
The above statement puts characterVariable consequences of a program in fail state are? All further
back into the istreamObject. input operations will be aborted and the output
The syntax for the peek function is: operations will display flawed results.
In real world programs, however, entering inappropriate
data may normally occur. For instance, in a software
The above statement returns the value of the first developed by C++ program, a user may enter
character in the istreamObject and assigns its value inappropriate data. In such cases, the program would
to characterVariable. become in fail state. However, this is not how a good user
interactive software is developed. The program should be
Let us consider the following code fragment. capable to reverse any wrong data input into a normal
working state. You may raise this question at this point: is
it possible to resume a normal input operation after the
program became in fail state? Of course it is. The next
topic will show us how.
On Line 1, a character variable c1 is declared and The clear function
initialized with what is going to be read by the Among the members of the istream class, the clear
cin.get(). The cin.get() on Line 1 makes the function, restores a program which is in fail state into a
program wait for a character to be entered. When a working state. However, to maintain a normal input and
character is entered, the get function on Line 1 removes output process, the unnecessary data in the input stream
it from the cin stream and assigns it to c1. This should be cleared first after the clear function is
character, which is assigned to c1, is put back into the invoked. This may be done using the ignore function.
cin stream by the putback function invoked by cin
The syntax for using the clear function is:
as it is done on Line 2. After Line 2, the first character in
the cin stream will be the character stored in c1.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 54


The clear function is best used with logical statements number of rows of score and name are defined to be
where a program continues with execution if appropriate 5.
data is entered or the program is cleared with clear
function and the program is ready for another execution Two for-loops are used in the program. One to for the
with another set of data. input part another for displaying the names and scores.
The first for-loop extends from line 8 up to line 30
We have now covered what we need to discuss regarding whereas the second for-loop is between lines 32 and 38.
the built-in functions which interact with the input and
output streams. But, we havent seen a full program in The body of the first for-loop starts by prompting the
which the latest functions which we discussed: ignore, user to enter a name. Then, there is a do-while loop
between lines 10 and 12. This loop is intended to discard
putback, peek and clear were used. The program
any white spaces before the entered name. It could also
below uses all of these functions. Some of the procedures
be done within a single line by using the ignore
in the program are just introduced to show how the above
function. The reason why the loop is introduced is to
function can be implemented in a program. There could
show how the putback function is used.
also be other straight forward approaches. Anyways, let
us have a look at it and discuss the basic points. In this do-while loop between lines 10 and 12, a character
Program 4.4[Correct].cpp is extracted from cin and assigned to the variable c by
using get function. The loop continues while the
character stored in c is equal to the white space character.
As soon as the variable c gets non-white space character,
i.e., after all the white spaces are discarded, the loop will
be exited. However, the last loop extracts and assigns the
first non-white space character to c. This character is part
of the name entered by the user. Therefore, it should be
put back into the input stream. The statement on line 13
performs this task using the putback function. Then,
the rest characters will be extracted by the getline
function on line 14 and will be assigned to the ith row of
name array, i.e., name[i].
On line 15, the user is prompted to enter the score for the
entered name. Note that, if the user enters a data which
doesnt correspond to float data type, the program will
become in fail state. If so, any further input operations
will be aborted. Dont you think this makes the user
irritated? Suppose you are using a software and you
entered a wrong data by mistake and the program stops
working as a result of that. Dont you get frustrated by the
software? You might be. Therefore, if you are a
programmer writing a code for a software and if you want
your software to be competitive, you should foresee such
issues. Then, what could be done in this particular
program to avoid a program in fail state? We can use the
clear function, right? But how do we know whether a
The above program will be used to prompt a user enter
wrong data was entered or not? We should check whether
five names along with their scores, store these user inputs
the data is entered correctly or not while the data is inside
and display the names and the corresponding scores. In
the input stream. Are there facilities in C++ to achieve
the program, a character variable c, a boolean variable
this goal? Of course there are. We can use the peek
isFailState, a float array score and a two-
function, right? That is what the if-statement on lines 16
dimensional character array name were declared from
and 17 will do. It checks what kind of data is in the cin
line 4 up to line 7 of the program. The variable
stream without removing the data. Note that the return
isFailState is initialized with false and the
value of the peek function is the ASCII value of the
character.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 55


If the first character in the input stream is a floating point The cin statement on line 27, extracts a value for the ith
number, its value should be between 1 and 9 (excluding row of score array once the program entered into a fail
scores which are less than 1). The peek function will state. The statement on line 29, discards one unwanted
now be used to check whether the character in the cin character. Can you guess what that unwanted character
stream is a whole number between 1 and 9. The ASCII could be? It is the white space produced by the extraction
numbers of the characters 1 up to 9 is 49 up to 57 in their operator on line 18 or the one on line 29. On line 30, the
respective order. Therefore, after the user entered a value value of isFailState is assigned with a value of
corresponding to score and if the first character in the false. Otherwise, the program enters the if-statement
input stream is a character with ASCII value outside the on line 19 on the next loop even if the user enters correct
above range, it will lead to a program in fail state. In these data.
cases, we need a flag within the program to indicate that
the program is going to be in fail state. Like the flag in The content of the second for-loop between lines 32 and
football games which will be raised when a ball crosses 38 is straight forward. The statement to note may be the
the boundary lines. In program 4.4, the flag is the while loop on line 34. This while loop is used to count the
isFailState boolean variable. After the user is number of characters in each row of the name array
prompted to enter the score and if the ASCII value of the before the null character. The number of characters is
first character entered by the user is less than or equal to determined by incrementing the value of an int variable j
48 or greater than 57, the value of isFailState until the null character is encountered. When the while
becomes true, otherwise its value will remain to be loop is exited, the value of j will contain the number of
false. In short, the if-statement on line 16 changes the characters for the ith row of the name array. Then this is
value of isFailState to true when the first used to insert the exact number of characters into the
character in the cin stream is not a number between 1 cout stream by using the write function. A cout
and 9. statement is used on line 36 to display the corresponding
score for each name.
On line 18, the extraction operator is used to extract the
input for the ith row of score. Note that, if wrong data is The above program may require further enhancements to
avoid all possible runtime problems. However, we have
entered, this statement will lead the program to be in fail
used it satisfactorily in order to see how some of the built-
state. If so, however, the if-statement on line 16 would
in functions in the istream and ostream classes are
have already foreseen this and would have changed the
value of the isFailState variable to true. If the used in a program.
value of isFailState is true, another if-statement Let us now have a closer look at how the output stream
extending from line 19 to line 28 executes the clearing and works. When data is fed to the output stream, it will not
brings the program into a working condition. send all the data to the output device immediately. It
keeps on storing the data in a buffer until the stream is
When the statement on line 18 makes the program to be
full. Sending the data to the output device only starts after
in fail state, the statements within the body of the second
the stream is full. Now, consider there is a power outage
if-statement will be executed. In this if-statement, the
after a data is inserted by a program to the output stream
program will be restored into a working condition by the
and before the output stream becomes full. What do you
statement on line 20 using the clear function. Then the
think will happen? The output device will not display the
ignore function used on line 21 discards the
data which the program is supposed to do. Because the
unnecessary characters in the cin stream. After this, the
data was still in the output stream waiting for the output
user is prompted to enter a correct score. Note that, at
stream to be full and to start being displayed on the output
this time too, the user may enter inappropriate data.
device. But, is there any way in C++ by which we can
Therefore, a while loop is used to loop until the user
force data in an output stream to be flushed to the output
enters a correct value for a float data type variable. The
device? Of course there is. The next topic will discuss how
truth statement for the while loop is the same as that of
this is done.
the if-statement on line 16. Within the while loop, the
unnecessary characters in the cin stream will be The flush function
discarded each time the user enters a wrong data. Actually, The member of ostream class, flush, forces any data
this could also have been done on line 16 itself instead of within the output stream to be sent to the output device
the if-statement and we could have avoided a few without waiting for the stream to be full. The syntax to
statements within the program. However, if statement is use the flush function is:
used on line 16 to show how the clear function works.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 56


If the flush function is invoked as in the above fill fills empty spaces of the allocated
statement, any data within ostreamObject will be character spaces for an output with designated
flushed to the output device automatically. character.
setf sets a specific flag for an output.
The concepts which we discussed so far deal basically unsetf reverses the flag set by setf
with how the input and output streams work and how function.
different functions interact with these streams. The flags returns the current formatting style or
majority of the built-in functions which we discussed sets formatting style contained by a variable.
mainly deal with extraction or insertion of data from or to
streams. None of them were used to deal with arranging All of the above functions are invoked by an output
the data in a formatted manner. However, some real stream (ostream class object) by using the member
world programming applications may require the outputs access operator. Now, let us see how the above functions
to be displayed in specific formats. For instance, a can be used in a program.
programming application which calculates the total price
The width function
of goods may need to be programmed to send a value in The syntax used for width function is:
exactly two decimal places to the printing device.
Some of the functions which we discussed previous may
be combined to have such formatted output. But, those The above statement allocates number character spaces
approaches would require more lines of coding. In for the very next output operation to the
programming, achieving the desired programming goal ostreamObject stream. If the number of output
with the fewest number of statements is usually characters to be displayed is greater than number, all the
preferable. Because, the more the number of statements, output characters will be displayed outside the boundary
the more vulnerable the program will become for errors. allocated by the width function. Let us consider the
In addition, fewer lines of coding make a program to be following piece of code:
neater. As a result, instead of using the functions in the
istream and ostream classes to have a formatted
input or output data, the other set of built-in C++
functions can be used. The outputs through put and
write functions are unformatted outputs and cannot be In the above piece of code two float variables x and y are
made to have a specific formatting style. declared on Line 1. The variable x is initialized with a
number which has two digits before the decimal place and
Formatting of outputs in C++ is usually done by using three digits (including the trailing zero) after the decimal
the built-in functions in the iostream file or in the place. Whereas the variable y is initialized with a number
iomanip file. The ios class in the iostream file has which has one digit before the decimal place and two
a number of functions which are used to arrange an digits after the decimal place. Note that the variable x has
output in a desired way. A similar formatting can also be six characters including the decimal point and the variable
done by the so called manipulator functions in the y has four characters.
iomanip file. However, the formatting functions in
both files have their own limitations and capabilities. On Line 2, ten character spaces are allocated for the next
Based on these limitations and capabilities, the functions output operation using the width function. Therefore,
which can achieve a desired formatting style for an output the very next output operation will be accommodated on
from either of the files can be selected at the the right side of these 10 character spaces. The output will
programmers discretion. be accommodated on the right side because by default an
output is displayed right-justified.
Formatting output using the ios class functions
The ios class in the iostream file has a number of On Line 3, the values of x and y are inserted into the
functions which can be used to have a specific format for cout stream using the insertion operators. Since the first
an output. Some of the functions in this class are listed output operation after the formatting on Line 2 is the
below. insertion of the value of the variable x into cout stream,
the value characters in the value of variable x will be
width allocates a specified number of
character spaces for an output. accommodated on the right side of the 10 character
precision puts the output in specified spaces allocated by the width function on Line 2. Note
number of decimal places. that the value of the variable x has six characters including

By: Asaye Chemeda Email: asayechemeda@yahoo.com 57


the trailing zero. However, trailing zeroes are not When character spaces are allocated for an output using
displayed in the output unless the format setting is the width function, the number of digits after decimal
changed to do so. Therefore, only five of the six places are fixed unless the setting is changed to display
characters (including the decimal point) without the more number of digits. But, some numbers, such as the
trailing zero will be accommodated within the 10 value of , may contain more than the default value of
character spaces. Therefore, the displayed output by the number of digits and it may be required to display all the
statement on Line 3 appears to be: digits.
In those cases, another function of the ios class can be
used. This function will be the next topic to be discussed.
In the above output, it can be observed that the value of
the variable y is displayed next to that of x without being The precision function
formatted. However, the trailing zero in the variable x is The syntax used for precision function is:
omitted in the displayed output. Since x has five
characters to be displayed and ten character spaces were
allocated for it, there are five unoccupied character spaces. The above statement sets number digits to be displayed
To understand a little bit more about how the width after the decimal place when an output is displayed from
function operates, let us consider the following piece of ostreamObject until the setting is changed. The
code. function can also be called without passing an argument.
In that case, it returns the current precision setting of the
program. The precision function will not force
trailing zeroes to be displayed.
The use of the precision function is shown in the
following piece of code.
The output of the above piece of code will look like:

Even if the width is set to 3 on Line 2 for displaying value


of x which has five displayable characters, all the five
characters were displayed. Therefore, if the number of The statement on Line 1 prints the current precision
displayable characters in an output is greater than the setting by using the precision function with empty
width set by the width function, the later will be parameters. If the precision has not been set before, this
overruled. statement will display a value of six for most compilers.
The statement on Line 2 indirectly prints the value of
On Line 4, another setting for width of an output is set. which is also equal to two times sine inverse of 1 in radian
In this case, 10 character spaces were allocated for the units. This line prints the output as below and there are
next insertion operation which is displaying the value of six digits after the decimal point.
square root of 3. Note that square root of 3 is an irrational
number and it has infinite number of digits. But, the
number of displayed digits after decimal places for most
compilers is six. Therefore, six digits will be displayed On Line 3, the precision setting is changed to ten digits
after the decimal place if there are no trailing zeroes and after the decimal point. The statement on Line 4 displays
if the setting for default number of decimal places is not the precision setting after it was changed on Line 3. This
changed. The value of square root of 3 up to six decimal will display a value of 10. The statement on Line 5 again
places is 1.732051. Which means that there will be 8 prints the value of after the setting is changed. The
displayable characters. However, 10 characters spaces are displayed output will be:
allocated. Which means that there will be two unoccupied
spaces. Note that when the width function allocates
character spaces, the counting for the allocated spaces
Now, the printed number of digits after the decimal point
starts from the very last character in the output stream
has become 10 as it was set by the statement on Line 3.
unless a newline character is introduced.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 58


Based on our discussion, can you answer what will be the width for the next insertion operation is set to 10.
displayed by the statement on Line 3 of the following The statement on Line 3 fills any unoccupied spaces with
piece of code? the * character by using the fill function. The value
of amount is inserted to cout stream as the first
insertion operation on Line 3. Since amount has only
five characters and since 10 character spaces are allocated,
it is expected that five of the spaces will be filled with the
Did you answer as 39.700? Or did you recall that the * character. The value of amount will be displayed as
precision function will not force trailing zeroes to be follows:
displayed even if the precision setting includes them? The
cout statement on Line 3 prints only 39.7 omitting the
trailing zeroes. The width function allocates six The unoccupied five spaces are now filled with the
character spaces put the four displayable characters on the character which is used as an argument when the fill
right hand side as follows. function is invoked. Note that the filling by fill
function takes place wherever there is an empty space;
whether it is in front of or inside or after the displayed
When the number of characters in an output are less than output value.
the space allocated by width function, there will be By the way, we do not have to take output formatting as
empty character spaces in the displayed output. However, a luxury topic. Some programming applications may
some programming applications may require to avoid require strict output styles. Therefore, detailed
such unoccupied character spaces when the output is understanding about the formatting facilities in C++
printed. For instance, unoccupied character spaces in might be vital. We have already discussed how some
bank checks may need to be avoided to prevent any formatting styles can be achieved. Besides, we have also
addition of extra digits in the unoccupied character noted some formatting styles which couldnt be handled
spaces. As a result, the empty character spaces may need by the functions which we discussed so far. For instance,
to be avoided. At the same time, a program application none of the formatting functions which we discussed
may need to set the width with small as well as large couldnt enforce the displaying of trailing zeroes. The
number of characters so that outputs with wide range of functions couldnt also change the justification of the
characters will be accommodated. Then, when outputs output. However, this doesnt mean that C++ doesnt
with small number of characters are printed, there will be have the facilities to handle those styles at all. Other styles
unoccupied characters spaces. In such cases, we can use which were not achieved by the previous ios class
another function from the ios class. This function will functions can be easily handle by setting different flags.
be discussed next.
In C++, flags are Boolean variables which signify that a
The fill function certain state is reached within the program. For instance,
The syntax used for fill function is: a state may be reached when right-justified output setting
is just to be changed to left-justified output setting. In
such cases, we need flags to indicate that a particular state
The above statement fills unoccupied character spaces is being reached. There are a number of flags for different
with character for the coming output operations to programming states. These flags can be set and unset
the ostreamObject stream. The value character thereby achieving some desired output style. How this is
can be a character literal or a character variable. The done will be the next topic to be discussed.
format setting by fill function persists until the setting
The setf , unsetf and flag functions
is changed. To see how the fill function operates, the
The setf function is an overloaded function and may
following code fragment will be considered.
have one of the following two forms:

In the first line of the above code, the double variable The syntax given in Form 1 takes one argument. By this
amount is declared and initialized with a number having
statement flag is set for the outputs through
five characters (including the decimal point). On Line 2,
ostreamObject and the flag will persist until it is
By: Asaye Chemeda Email: asayechemeda@yahoo.com 59
unset. As part of the argument the function name where Program 4.5[Correct].cpp
the flag belongs (ios) and the scope resolution operator
(::) should always precede the flag.
The syntax given in Form 2 takes two arguments. By
this statement previous settings corresponding to flag2
will be cleared first and flag1 will be set as a flag for the
coming output operations into ostreamObject and
the flag given by flag1 will persist until it is unset. Both
arguments should be preceded by the function name
where the flag belongs (ios) and the scope resolution
operator (::).
A number of flags can also be combined as a single setf
function argument using the OR operator. This avoids
writing multiple lines which could be written to change
the setting for each flag. The syntax for such setf
function with combined flags when invoked by the cout The output for the above program is shown below. Since
stream is given below. the only formatting functions used in the above program
are width and fill and since the effect of these
functions was discussed in detail, no further discussion
The frequently used flags in ios class are: will be made on the output.
left makes the output left-justified.
right makes the output right-justified.
showpoint enforces displaying of trailing zeroes.
showpos displays the + sign when positive numbers
are displayed. Now, let us introduce the left, showpoint and
fixed puts the output in fixed number notation. showpos flags in the program and analyze the output. A
scientific puts a floating-point output in scientific Boolean variable isPrintComplete was also
notation.
declared and initialized with a value of false. This
boolalpha allows input and output of Boolean
variable attains a truth value of true after all the desired
values by using the keywords true and false.
dec displays an output as decimal (base 10) number. output are printed.
oct displays an integer output as octal (base 12) Program 4.6[Correct].cpp
number.
hex displays an integer output as hexadecimal (base 16)
number.

The following flag groups consist of more than one flag


and can only be used as a second argument in the setf
function which takes two arguments.
adjustfield refers to the left and right flags.
floatfield refers to the fixed and
scientific flags.
basefield refers to the dec, oct and hex flags.

The frequently used flags which can be set to display an


output in different styles are given above along with
explanations what the specific effect of each flag is.
Instead of looking into pieces of codes to discuss how
each of the flags affect an output setting, let us write a
program and analyze the displayed outputs. For this, let
us consider the following program first and the resulting
output.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 60
In the program, the statement on line 9 clears all Program 4.7[Correct].cpp
ajustfield flags and sets the left flag to be the
used as a justification flag for the outputs. By default,
C++ outputs are right-justified, i.e., they are written on
the right hand side of the allocated space. As can be seen
from output of program 4.5, all the outputs are printed on
the right hand side of the allocated space. However setting
the left flag puts them on the left hand side of the
allocated spaces and the unoccupied spaces will be shifted
to the right side. Which means that characters used as an
argument of fill function will be on the right hand side.
On line 10, the showpoint and showpos flags were
combined using the OR operator and passed as an
argument to setf function. Therefore, after this line
trailing zeroes will be displayed and the + sign will be
shown for positive values.
On line 23, the value of isPrintComplete is
changed to true. On line 24, the value this Boolean
variable is printed. Normally, C++ programs consider
Boolean variables to be 1 for true and 0 for false.
Since the value of isPrintComplete at the time of
its printing is true, the cout statement displays 1 and On line 8 of the program, all the flags corresponding to
the showpos flag set on line 10 adds a + sign before the basefield are cleared first and the hex flag is set.
value. If it is desired to print the value of Therefore, integer values will be displayed in hexadecimal
isPrintComplete as true or false, the numbers. On line 9, the scientific flag is set. Note
boolalpha flag should be set. that, the floatfield flag group could also be used as
The output for program 4.6 is shown below. The outputs a second argument on line 9. However, mentioning the
are left-justified, the empty spaces on the right hand side second argument is mandatory only when it is desired to
are filled, the + sign is added and the trailing zeroes are clear all the previous settings for the flags corresponding
to the group.
displayed.
The outputs will now be displayed in three columns. The
second column displaying the output of an int data type
price array whereas the third column displays the
output for float data type price2 array.
The boolalpha flag is now set on line 27 and the
Let us consider again the Program 4.6 where the left, output of the isPrintComplete variable on line 28
showpoint and showpos flags are substituted by will be the keyword true.
hex and scientific flags. Since the hex and oct
flags operate only on int data types, two arrays, one with The output of program 4.7 is shown below. In the output,
int data type and another with float data type, were characters are right-justified, empty spaces are filled, int
declared. On the other side, the scientific flag data type values are displayed in hexadecimal numbers
operates only on floating-point data types. and floating-point values are displayed in scientific
notation.

Once a flag is set, the setting can be reversed by using


unsetf function when the flag is no longer required or

By: Asaye Chemeda Email: asayechemeda@yahoo.com 61


to return to the default setting for that particular flag. The Form 2 sets the flag for outputs through
syntax used for the unsetf function is the same as that ostreamObject to flagVariable.
of setf function. The only difference is the unsetf
The following program shows how flag variables and the
function is not overloaded to take two arguments. The
flags function can be used.
following statement reverses flag setting to the default
setting for outputs through ostreamObject. Program 4.8[Correct].cpp

For instance, the following statement clears the left-justify


setting and returns the justification setting to the default
setting.

The unsetf function also takes flags combined with


OR operator as an argument. In which case, all the flags
combined by the OR operator will be set to their default
setting. The following statement clears the showpoint
and showpos flags.

In the above program, the statement cout.flags()


We have seen that by setting and unsetting different flags, on line 4 returns the current flag setting of the program
we can display outputs in different formatting styles. and assigns it to f1 variable. Since no flag was set in the
Now, let us see the strong side of the functions in ios program before the statement on line 4, f1 will contain
class which cannot be attained by the formatting the default flag setting. On line 5, another flag variable f2
functions in the iomanip file. was declared. This flag variable will contain the combined
showpoint, showpos and left flags.
The main advantage of the flags in the ios class is that
they can be assigned to a variable with fmtflags data On line 7, a minimum width of 10 is set for the output
type. Consequently, any particular flag setting which is on line 8. Note that, until line 8, the flag setting is the
assigned to a variable can be used to set a flag anywhere default flag setting used by the compiler. Therefore, when
in the program by using the variable. Combined flags can the value of 100.10 is printed by the cout statement
also be assigned to variable. The syntax to create a flag on line 8, it will be right-justified, and trailing zeroes will
variable is: be omitted.
On line 9, the flag setting is altered by using the flags
function to the flag settings contained by the f2 variable.
In the above declaration, a combination of flag1, Again, the minimum width is set to 10 by using width
flag2 flagN is assigned to variable f which is of a function on line 10. As a result, when the value of
fmtflags data type. 100.10 will be displayed by the cout statement on line
11, it will be left-justified, trailing zeroes and the + sign
Once a flag variable is declared, it can be used at another
will be displayed.
place of the program. For this, the flags function can
be used. The flags function is overloaded and it has On line 12, the f2 flag setting is cleared by using
one of the following two forms: unsetf function. Which means that when the value of
100.10 is printed, the default flag setting will be used.
The output of the above program will look like:

The syntax given in Form 1 returns the current flag setting


of ostreamObject. Therefore, it can be assigned to Controlling how the output is displayed through ios
variable with fmtflags data type. The syntax given in class functions was exciting, right? Of course it was.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 62


Besides, the formatting procedures are very applicable for difference is the manipulator functions cannot be
real world programming too. The ios class functions assigned to a variable but the ios class functions can. In
have their strengths in being assigned to a flag variable. addition, the manipulator functions can be concatenated
Despite this, they have some shortcomings as well. The by using the insertion operator on a single output stream
main limitation of the ios class formatting functions is whereas the ios class functions cant. Therefore, no
that they have to be always written as a separate statement; further separate discussion will be made for each of the
each statement requiring the output stream to invoke the functions. However, mentioning the flags in the
function. Which means that they cannot be embedded iomanip file is vital and the most frequently used ones
within insertion operators where one output stream are listed below.
invokes a number of functions. As a result, several lines
of coding is required making the program to be error left makes the output left-justified.
right makes the output right-justified.
prone.
showpoint enforces displaying of trailing zeroes.
Dont you think it is better if the functions could be noshowpoint turns off the showpoint flag.
embedded within the insertion operators? Wouldnt this showpos displays the + sign when positive numbers
avoid several repetitions of separate invocations the are displayed.
functions by the output stream? The ios class functions noshowpos turns off the showpos flag.
would definitely be more versatile if they could be fixed puts the output in fixed number notation.
embedded within the insertion operators. But, they scientific puts a floating-point output in scientific
notation.
already have their strong sides. Their limitation is
boolalpha allows input and output of Boolean
possessed while their strong side is lost by the so called
values by using the keywords true and false.
manipulator functions in the iomanip file. Are you
noboolalpha turns off the boolalpha flag.
ready to learn the functions in this file? As most of this dec displays an output as decimal (base 10) number.
functions have an equivalent from the ios class, oct displays an integer output as octal (base 12)
understanding how the manipulator functions will be number.
used is very easy. hex displays an integer output as hexadecimal (base 16)
number.
Formatting output using the manipulator functions
The iomanip file has a number of functions which can
be used change the formatting styles of an output. In To see the equivalency between the manipulator
order to use these functions within a program the functions and the ios class functions, we will format the
iomanip file should be included in the program. Some output for Program 4.7 using manipulator functions.
of the functions in this file along with the equivalent ios When the output of Program 4.7 is entirely formatted by
class functions are listed below. the manipulator functions, the program will appear to be
as follows. Note that the iomanip file is included in the
setw allocates a specified number of character
program.
spaces for an output. [Equivalent with width]
setprecision puts the output in specified Program 4.9[Correct].cpp
number of decimal places. [Equivalent with
precision]
setfill fills empty spaces of the allocated
character spaces for an output with designated
character. [Equivalent with fill]
setiosflags sets a specific flag for an
output. [Equivalent with setf]
resetiosflags reverses the flag set by
setf function. [Equivalent with unsetf]
endl displays the next output on a new line.

All of the above functions are invoked by an output


stream (ostream class object) by using the insertion By the statement on lines 9 and 10 of program 4.9, the
operator. The way how the above functions are used in a flags in basefield are turned off and the hex and
program is the same as the way how the equivalent scientific flags are turned on. Notice how the
functions in the ios class are used. A significant resetiosflags and the setiosflags are

By: Asaye Chemeda Email: asayechemeda@yahoo.com 63


concatenated using the insertion operator on a single same sequence of formatting operations are frequently
cout stream. In program 4.7, this was done by separate used in a program. This avoids repetitions of codes
statements. making the program neater as well as less error prone.
The statements from line 10 up to line 15 of program 4.7 The output setting achieved in Program 4.8 by assigning
are combined by a single statement on line 11 of the flags to flag variables can exactly be replicated with the
program resulting in the same effect on the output. Note following program.
how the setw function replaced the width function for
Program 4.10[Correct].cpp
the same arguments. Inside the for-loop, the statements
from line 17 through line 24 of program 4.7 are replaced
by a single statement on line 14 of program 4.9. The
setfill function inside the for-loop of program 4.9
replaced the fill function in program 4.7. The two
statements which were used to set the boolalpha flag
and display a Boolean variable in program 4.7 are now
reduced to a single statement line 18 of the program.
Note that the output of program 4.9 is displayed in exact
the same setting as that of program 4.7. However, the
possibility for concatenation of the manipulator functions
allowed to have fewer statements in program 4.9. This
shows the edge that the manipulator function have over
the ios class functions in having fewer number of
statements and therefore less error prone program.
However, if we refer program 4.8 and notice how the
functions in ios class can be assigned to a variable, we In the above program, two sequences of manipulators
understand that the ios class functions have an edge customSetting and defaultSetting were
over the manipulator function as well. This disadvantage defined. The customSetting has the same setting as
of the manipulator functions, however, can be improved flag variable f2 of program 4.8 with the exception that
by defining sequence of manipulators. The syntax to customSetting allocates 10 character spaces for the
create such customized sequence of manipulators for an
output. The customSetting turns on the
output stream is:
showpoint, showpos and left flags whereas the
defaultSetting does the opposite but it also
allocates 10 character spaces for the output.
The main function extends from line 18 to line 23 of the
program. On line 19, the value 100.10 is printed by first
The above syntax is just like defining a function which invoking the defaultSetting sequence. The task of
returns and receives by reference in which ostream is this statement is just like printing the value with the
the return type of the function and the data type of the default compiler format setting except that the width is
parameter, name is the function name and variable set to 10. On line 20, the value 100.10 is printed by first
is the argument. The name and variable can be any invoking the customSetting sequence. Since the
qualified identifiers. On the last line of the definition of format setting in customSetting combines the
the sequence of manipulators, variable should be statements on line 9 and 10 of program 4.8, calling the
returned. Within the body, any output formatting sequence will have the same effect on the output as the
operations by either the manipulator functions or the mentioned lines of program 4.8. On line 21, the value
ios class functions can be included considering 100.10 is printed by invoking the defaultSetting
variable as an output stream. sequence first. This will have the same effect as lines 12
through line 14 of program 4.8.
Once the sequence of manipulators are created as above,
name can be used within extraction operators to enforce Note that within the defaultSetting and
the format settings included in the body of the definition. customSetting sequences, ios class functions
Creating sequence of manipulators is helpful where the could also be included. However, the above program was

By: Asaye Chemeda Email: asayechemeda@yahoo.com 64


intended to show how the shortcoming of the Other characters than the format specifiers can also be
manipulator functions can be improved by creating included in the first argument of printf function. Let
sequence of manipulators. As a result, only manipulator us consider the following statement.
functions were used in the sequences.
Through the ios class and manipulator functions, we
have seen how outputs can be formatted using different In the above statement, there are two format specifiers in
styles. Wasnt it interesting? Indeed it was. But, they are the first argument, %d and %s. The inclusion of additional
not the only functions used in C++ to format outputs. characters in the first argument is also legal. When the
C++ program has adopted another function from C to output is displayed on the screen, the arguments outside
format outputs with wide range of data types. This the double quotes will replace the places occupied by the
function is versatile and discussing its application is very format specifiers. However, the arguments outside the
useful. double quotes should be placed in the same order as they
are put in the first argument. An integer first and a string
The printf function next. The above statement displays the following on the
One of the derived functions from C program, printf, output.
can be used to print a formatted output to the console.
This function is best used when printing combination of
different output data with different format settings at As can be seen from the output, the second argument, 3,
once is required. The function is overloaded to receive
replaced the %d specifier in the first argument and the last
different number and data types of arguments. In order
argument, C++ replaced the %s specifier.
to use the function, the stdio.h file should be included
in the program. The format setting for some data types can also be
adjusted by introducing numbers between the % sign and
The general syntax to use the printf function in a
the format code. These numbers can be a single integer
program is:
or two integers separated by a dot. The effect that putting
numbers between the % sign and the format code depends
on the data type. The number 0 can also precede the first
In the above syntax, the formatSpecifier basically integer. The number between the % sign and the format
contains one or more format specifiers along with other code is generally put as 0x.y, where x and y are integers.
characters. Each format specifier contains the percent The preceding 0 is used to fill empty character spaces with
sign (%) followed by format code. The format code 0. The value of x represents the minimum allocated
depends on the data type which is going to be printed by character spaces for any data type. The meaning of y is
the function. Among many format codes, c stands for different for different data types. For integers, it
characters, d for signed integers, f for floating point represents the minimum number of digits. If the integer
values, s for strings, p for pointers, e for scientific contains less digits that y, the 0 characters will precede
notation and x for hexadecimal numbers. The rest the number. For floating point data types, it represents
arguments, variables, will contain the same number the number of digits after decimal places. For strings, it
of variables as the number of format specifiers. The represents the maximum number of characters.
variables should be separated by a comma and placed in
the same order as the order of the format specifiers placed The following statement displays the number
within the first argument. 1298.567 with 9 character spaces and 2 digits after the
decimal point and fills any empty spaces with 0.
The following statement prints 1m on the screen.

The output of the above statement is:


The first argument in the above statement contains two
format specifiers, %d and %c. Therefore, two other
arguments matching these format specifiers. Since the
The following statement displays the number 1000 after
format code d stands for integers, the first argument after
the string Output with 10 character spaces and 5
the format specifier should be an integer. The other
digits within the allocated character spaces.
argument should be a character as the format code c
stands for characters.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 65


The output for the above statement looks like: for-loop. When the above program is run, the displayed
output is:

When an output is displayed using the printf function,


it is right-justified. In order to display the output left-
justified, we need to put minus (-) sign just after the %
sign.
Isnt the printf function efficient in formatting
The following statement allocates a minimum of 15 outputs? Of course it is. The way how the function
character spaces and prints a maximum of 10 left- integrates a string message with other variables of
justified characters from the Programming string. different data types is also superior to the functions in
iostream file or iomanip file. However, it has a
severe limitation. In contrast to the iostream file or
The output of the above statement is shown below: manipulator functions, which can display outputs to wide
variety of output devices, the printf function can only
display an output to an internal displaying device, which
is usually the screen.
The above output is left-justified. Only 10 of the 11
characters in the string are printed in the 15 allocated Speaking of, we havent yet discussed about input and
character spaces. output operations beyond the default input device
(keyboard) and output device (screen), right? However, at
The printf function is very helpful in order to the beginning, we have said that the input and output
concatenate a string message with variables of different streams in C++ can interact with any type of input or
data types with a specified format setting. It avoids output device. Among the many input or output devices,
invoking a number of formatting functions in the ios however, using files as an input source or an output
class or iomanip file. For instance the following destinations is frequent task which a programmer often
program has a closer effect on the printing of price and encounters. Therefore, it is worth discussing about how
price2 arrays given in program 4.9. input and output operations on files is done separately.
The next topic discusses this concept in detail.
Program 4.11[Correct].cpp
File Input and Output (I/O)
Using files as an input source and an output destination
might sometimes become preferable to input and
operations on standard input and output devices. If an
input data involves several characters, using the keyboard
to enter the bulky data every time the program runs might
become tedious. In those cases, the input data may be
stored in files and the program can be made extract the
input from the file. This avoids the tedious typing process
and the accidental errors which may occur in doing so.
Displaying the output to the screen has also certain
The statement on line 8 of the above program avoids the limitations. First, the screen accommodates limited
multiple invocations of the setw function on line 11 of number of characters for display. Therefore, when there
program 4.9. Although filling the empty spaces with is a large data to display, the screen is unusable and using
designated characters could not be replicated, the files becomes very handy. Second, the outputs made on
statement on line 11 of the program 4.11 again avoids the the screen cannot be saved and cannot be used at a later
multiple invocations of the setw function used on line time or as an input for other applications.
14 of program 4.9. The statement on line 14 of program
4.11 shows that how the printf function easily Due to the above limitations of I/O operations on
integrates a string message with a variable used in the standard devices, files are often used to read input from
program. This statement displays the number of items and write an output to. Input and output operation on
printed by using the last value of the counter used in the files are much similar to those on standard devices. There
are notable distinctions though.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 66


The input and output streams for I/O operations on
standard devices are created as soon as the program starts
execution. As a result, manual creation of the input and
output streams is not necessary. On the other hand, the After the above declarations, inputStream will be
input and output streams to read data from or write to used as an input stream like cin to read data from files.
files should be created manually within the program. The outputStream can be used as an output stream
Creating these streams is not that difficult though. like cout to write data to files. The ioStream can be
Besides creating streams, another notable distinction used as both input and output stream to read from and
between the I/O operation on standard devices and files write to files.
is that both the input and output streams for file I/O The important property of file input and output streams
should be associated with the files which they operate on. is that they can only interact with only one file at a time.
Otherwise, I/O operations on files and on standard If the program requires to interact with more than one file
devices are much alike. In addition, most of the functions for either the input or the output stream at the same time,
which are used to integrate the streams with the program the same number streams should be created and each of
for standard devices can be used for files as well. them should be associated with a single file at a time. But,
an input or output stream can be used to interact with
As the iostream file handles the input and output another file after being dissociated with the first file.
streams for I/O operations on standard devices, the
fstream file handles the input and output streams for Association of a file with a stream
file I/O. Therefore, whenever file I/O operation exists in Another important step in file I/O is associating each
a program, the fstream file should be included in the stream with the file with which it interacts with. The input
program. stream should be associated with the file from which data
is read. The output stream should be associated with the
Typical file I/O operation involves the following four file to which a data will be written. This can be done in
steps: one of the two approaches available in C++. The first one
is by using the open() function. The second approach
1. Creation of a stream
is including the file name during the stream itself. The
2. Association of a file with the stream
syntax for both approaches is shown below.
3. Operation on the file
4. Dissociation of the file with the stream.
Each of these steps will be discussed one by one. In an
object-oriented approach, the first and the second steps
can be combined. Since this approach is not that The above approach uses the open() function to
complicated either, it will also be included in our associate the file which has fileName with the
discussions. corresponding stream.

Creation of a stream
Three types of streams can be created for file I/O. An
input stream for input operations, an output stream for
output operations and an input/output stream for both
input and output stream operations. Each type of the The above approach simultaneously creates streams and
streams is created by declaring a variable with the data associates them with the file which has fileName.
type of the class corresponding to the stream. The class
corresponding to the input stream is ifstream. If the file is not in the same directory as the directory
which the program points to, the full path should be
Whereas, the class corresponding to the output stream is
mentioned with fileName. If a file with a specified file
ofstream. The fstream class corresponds to
name is not available in the directory, the input stream
input/output stream. Once a variable is declared with a
leads to a program in fail state while the output stream
data type of these classes, it will be used as a stream like
creates a new. Therefore, including a code which checks
the standard streams such as cin and cout. The name
the availability of the file with the specified file name in
of the variable can be any qualified identifier.
the program is important to avoid a possible input stream
The syntax to create an input, output and input/output failure. When an output stream interacts with an existing
streams is: file as shown above, it first erases all the data in the file.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 67


Operation on the file argument is a parameter which describes the mode how
Once a file is associated with a stream, any valid operation the file will be opened. In the function definition, the
can be performed on the data extracted from the file. The second argument is initialized in the formal parameter list.
output results can be send to a file. Suitable formatting As a result, passing the second argument is optional. A
styles can also be applied to the output. For this, the number of alternatives are available for the mode. These
functions in the iostream class or fstream class can alternatives are listed as follows along with their
be used. In general, after associating a file to a stream, the explanation.
normal C++ procedures can be applied with the data
extracted to the program as an input and to the data sent ios::in specifies that a file is capable of input.
to the destination as an output. The functions which are ios::out specifies that a file is capable of output.
peculiar to file I/O will be discussed briefly while the ios::app appends an output to the existing data in
functions which are used for I/O operation on standard the file. It is used for output capable of output only.
devices will be reviewed. ios::ate points to the end of file (EOF) when the
file is opened.
Dissociation of a file from the stream ios::binary opens the file in binary mode.
After the necessary I/O operation is performed on files, ios::trunc erases all the data in the existing file.
they should be dissociated from the stream. This may
have several advantages. First, the stream which is
dissociated from a file can be used for another I/O. The above modes can be combined with the OR operator
Second, the dissociation flushes any remaining data in the in order to have more than one effect. The default values
stream and the file can be used for further activities. for this modes are ios::in for ifstream,
ios::out|ios::trunc for ofstream
The dissociation of files from a stream is done by using ios::in|ios::out for input/output fstream. If
the close() function. This function doesnt take any instead of the default second argument for ofstream,
arguments. It is invoked by the stream for which the the ios::app is used with any other mode but the
dissociation is going to be done with the member access
ios::trunc, the existing data in the file will be
operator. The syntax to dissociate a file from an input,
preserved during output.
output and input/output streams is:
Let us now consider the following program to see how
creation of streams, association with streams, working on
the files and dissociation is done.
We have covered the basic steps in file I/O. It was Program 4.12[Correct].cpp
fascinating! Wasnt it? File I/O is as interesting as I/O
operation to standard devices. Now, let us discuss the
functions which are often used in file I/O.
The open function
We have seen that the open function is used to associate
a file with the stream. Here, we will discuss the features
of the function which were not discussed before.
After an input stream invokes open function, the stream
may evaluate true in Boolean expressions if the file which
is passed as an argument exists and EOF is not reached
in the file or false otherwise. Thus, the input stream can
be used in a code that checks whether the file exists or not In the above program, the fstream file is included on
so that further actions can be taken depending on the line 2. On line 5, an input stream input is created. On
outcome. At the same time, the input stream returns true line 6, an output stream output is created. After that,
when the EOF is not reached or false otherwise. This on line 7, input is associated with a file name
concept can be used as a logical expressions so as to limit Input1.txt. This file exists in a directory named
the input stream from trying to extract data beyond EOF. files which by itself exists in the working directory of
the program. Therefore, the whole path is passed as an
The open function actually takes two arguments. The first
argument during the association. Note that two back-
argument is always the file name. Whereas, the second

By: Asaye Chemeda Email: asayechemeda@yahoo.com 68


slashes are required to change directory: one the escape existing file or false otherwise. The syntax to use the
operator the other the actual back-slash. function is:
On line 8, output is associated with a file named
Output1. This file exists in the same directory as
Input1. Two arguments are passed for the open In the above statement, the is_open function returns
function during the association. The second argument true if stream (which can be any stream) is associated
ios::app overrides the default arguments with an existing file or false otherwise.
ios::out|ios::trunc. As a result, when an Once we have seen how we can check whether a file exists
output is sent to the output file, the original content will or not, let us focus on the functions which are often used
not be erased. Rather, an output will be appended to the for operations on files. One of the most frequent
existing data. operations on input files is to check whether the end of
The if-statement between line 9 and 11 checks whether the file (EOF) is reached or not during extraction.
the Input1 file exists or not. If the file exists in the Because extracting data from input file usually takes place
specified directory, input will evaluate true. until EOF is reached. One of the ways to do this is to use
Otherwise, it evaluates false. If the case is the latter the input stream identifier in a logical expression. But, is
one, the program displays the message The file there another way? The following topic answers this.
doesnt exist!. The eof function
A member of the ios class, eof function, returns true
On line 12, the first data is sent to the output file by using
the insertion operator on output. The string The when end of file is reached or false otherwise. The
function is invoked by a stream with the member access
first output message! will be sent to the file.
operator. The syntax to use the eof function is:
If the output file has already other data, the string will be
appended to the existing data. This is due to the second
argument passed to the open function. On line 13, the
string This one is appended! will be appended The above statement will evaluate to true when EOF is
to string sent on line 12. reached in the file associated with stream. Therefore, an
input stream should only extract as long as negation of the
On lines 14 and 15, input and output are dissociated from above statement returns true.
the files which they have been interacting with. After this,
the streams can be associated with other files for further Since an attempt by a program to perform input operation
I/O operations. beyond EOF results in an error, detecting whether an
EOF is reached or not is a common activity in dealing
Isnt file I/O so simple? It even makes the basic principle with reading data from files. Normally, the I/O operation
of C++ I/O operations more clear. Do you also feel the on files takes place in sequential order. But, what if we are
same? Or do you want to wonder more? Let us now have interested to point to specific location where the next I/O
a look at other functions which are frequently used in file operation will take place within a file? Or what if it is
I/O. In program 4.12, we have seen how the existence of desired get the current location where I/O operation is
an input file is checked by using the input stream itself. taking place? The next topic gives clues about these.
There is also another way to do this. In addition, what if
we want to check an output file exists or not. The The seekg,seekp,tellg and tellp functions
identifier of an output stream cannot be used in the same The seekg and seekp functions respectively are
way as the identifier of the input stream was used to check members of the ifstream and ofstream classes
whether an output file exists or not. In those cases, C++ which are used to point a specific location in the files
has a built-in function which checks the existence of an associated with the respective streams. The seekg
input file. This function will be the next topic. function is called get pointer and the seekp function is
known as put pointer. Both the functions take two
The is_open function
arguments. In both functions, the first argument specifies
A member of the fstream, ifstream and
an integer offset from the file location specified in the
ofstream classes, is_open function, checks whether
second argument. The value offset represents the number
a stream is associated with an existing file or not. It works of bytes to be passed from the location specifier to the
with any stream and is invoked by the stream using the next point. The syntax for the functions is as follows:
member access operator. The function takes no
arguments returns true if the stream is associated with an
By: Asaye Chemeda Email: asayechemeda@yahoo.com 69
Now, let us see a program which implements some of the
latest concepts which we discussed about file I/O. Before
looking into the program, let us prepare a folder named
The value of offset can be any integer: a positive value MyFile in the C-drive. Within this folder, let us create
indicating an offset in forward direction whereas a two files iFile.txt for the input file and
negative value meaning an offset in the backward oFile.txt for the output file. In the iFile.txt, let
direction. The location can have one of the following us write the following characters:
three location specifiers. 1,2,3,4,5,6,7,8,9...ThisMessageWillBeReversed!

ios::beg location specifier for beginning of The file will now look like:
file
ios::cur location specifier for current
location
ios::end location specifier for end of file
The program which uses iFile.txt as an input file
and oFile.txt as an output file is:
Even if the seekg and seekp functions are useful in
pointing to a specific file location within a file, Program 4.13[Correct].cpp
determining the value of an offset is usually too sensitive
for a programmer to handle when the file is in text mode.
This is because a number of character translations into
bytes will take place by the compiler when a file is opened
in text mode. As a result, in files opened in text mode,
every character including white spaces, tabs and new lines
will have their own translations. And it is difficult for a
programmer to keep track of these and predict where
exactly the program might point. As a result, these
functions are not often used with files opened in text
mode. However, for files opened in binary mode, the
functions can easily be used.
Sometimes it may be desired to get the current location
where I/O operation is taking place. In those cases, the
tellg and tellp functions become useful. The
tellg function returns the current location of input
operation on the input file and tellp is its counterpart
for an output operation on the output file. The syntax
used for these functions are:

In the above program, an input stream in and an output


The functions which we have seen so far about file I/O stream out are created on lines 5 and 6 respectively. Two
deal with associating, dissociating, detecting, or pointing integer variables i and sum and one character variable c
within the input and output files. Now, let us discuss the were declared on the subsequent lines. On line 9, the input
two familiar concepts: extracting from an input stream stream is associated with the input file by passing the full
and inserting into an output stream. Do you remember path of the iFile.txt file. On the next line, the same
the functions which we used to achieve this for standard task is done to the output stream.
I/O operation? To mention few, we used the get, put,
getline, read, write, ignore, peek, putback The if-statement on line 11 checks whether in is
and flush functions. These functions can also be used associated with an existing file or not by using the
for file I/O operation in the same way as they were used is_open function. If not, it displays The file
for standard I/O. Therefore, there will not be any further doesnt exist! message on the output device
discussion about the functions.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 70
which is connected to the cout stream, which is the assigned to the character c which is then sent to the
screen. oFile.txt. Since file I/O normally takes place in
sequential order and since the output stream is not made
The do-while loop between lines 13 and 16 determines
to point to any nonsquential location, the statement on
the sum of the numbers written in the iFile.txt file.
line 23 appends the value of the character c to the existing
Here is the detail. On line 14, the in stream extracts a
data in the output file. The logical expression of the do-
value and assigns it to an integer variable i. Recalling the while loop uses the peek function to look into what is
rules of the extraction operator might be useful here. The the next character inside the input stream (without
extraction operator extracts data only until it encounters removing it) and compares it with the dot character. The
a character within the stream that doesnt correspond to loop will continue until next character in the input stream
the data type of the variable on the right hand side of the becomes equal to the dot character. Note that the
operator. In the input file, the first character is 1, which iFile.txt file will be navigated in the backward
is an integer. The next character is a comma, which is not direction starting from EOF until a dot is encountered.
an integer. Therefore, the extraction will be terminated
when the extraction operator encounters this comma. As On line 25, the variable i is initialized with zero and on
a result, the extraction in the first loop will be terminated line 26 the input stream is made to point to the beginning
after extracting 1. This value will then be assigned to i. of the file by using the seekg function. Now, starting
from this point, the while loop between lines 27 and 29
On line 15, the value of i is added to sum which was
loops until EOF is reached. This will be detected by the
initialized with zero. The in.get()statement, within eof function in the logical expression of the while loop.
the logical expression of the statement on line 16, extracts Inside the loop, the in.get() statement on line 28
the next character in the input stream and removes it from
removes one character from in and makes the input
there. The first character which this get function
stream progress towards the EOF while the value of i is
encounter is the comma which couldnt be extracted by
incremented by 1 indirectly counting the number of
the extraction operator on line 14. This character is
characters in iFile.txt. On line 30, a data is sent to
compared with a dot. If the character which is extracted
the output file about the number of characters in the
and removed from input stream by in.get() is equal
iFile which is counted by the while loop between lines
to the dot character, the do-while loop will be exited
27 and 29. The next lines dissociate both the input and
otherwise it goes back to the statement on line 14 for
output streams from the files which they have been
another loop. This process will be repeated. The
interacting with.
extraction operator extracts the integers between the
commas while the in.get() statement in the logical When the above program is run, the output function will
expression of the do-while loop extracts the commas. The appear to be:
extracted integer will be assigned to i and summed to the
previous value of sum. The loop will terminate, when the
in.get() statement encounters the dot character after
all integers.
On line 17, the first set of data will be sent to the output
file through the output stream out by using the insertion The content of the output file is just as expected. The sum
operator. The message within the double quotes on line of the numbers 1 up to 9 is 45. The reversed message is
17, the value of sum and a new line character will be sent displayed and the number of characters were counted.
to the output file, oFile.txt.
We have now covered what we need to discuss about
On line 18, the variable i is initialized with zero;to be input and output operations in C++. No matter how
used as an incremented variable in the do-while loop elegant a program we wrote is, if it is fed with a wrong
which extends between lines 19 and 24. In this do-while data or if it displays a wrong output due to mismanaged
loop, the value of i is incremented by 1 on line 20. Then, input and output operation, our program will become
on line 21, the input stream is made to point to a location useless. Therefore, the long discussion we made on this
in the backward direction with an offset of 1 starting from topic is justified. Not only that, it gave us the core
the end of the iFile.txt by using the seekg knowledge about how interacting with C++ streams and
function. If we look at the end of the input file, the data formatting is done. At the same time, it was pulsating.
character what we get is the ! character. This will be Wasnt it?
extracted by the get function on line 22 and will be
By: Asaye Chemeda Email: asayechemeda@yahoo.com 71

S-ar putea să vă placă și