Title: ACS 168 Structured Programming Using the Computer
1ACS 168Structured Programming Using the Computer
- Joaquin Vila
- Chapter 5
- Spring 2002
- Prepared
- by
- Shirley White
2Chapter 5I/O Streams as an Introduction to
Objects and Classes
- In this chapter, we will examine
- I/O Streams and Basic File I/O
- Tools for Stream I/O
- Character I/O
- Inheritance
3I/O Streams as an Introduction to Objects and
Classes
- I/O refers to Input and Output.
- Input refers to data flowing INTO your program.
- Output refers to data flowing OUT OF your
program. - Input can be taken from the keyboard or a file.
- Output can be sent to the screen or to a file
- Input is transferred to a C program from either
a file or the keyboard by means of an input
stream. - Output is transferred from a C program to the
screen or to a file by means of a output stream. - Streams are objects defined in the Standard
Librarys header files ltiostreamgt and ltfstreamgt.
45.1 Streams and Basic File I/O
- A stream is a flow of characters (or other kind
of data). - Data flowing INTO your program is an input
stream. - Data flowing OUT OF your program is an output
stream. - We have dealt with two of the three standard
streams already cin and cout. - If in_stream and out_stream are input and output
streams, we could write - int the_number
- in_stream gtgt the_number
- out_stream ltlt the_number is ltlt the_number ltlt
endl
4
5Why Use Files for I/O?
- In a word, files are permanent storage.
- Your program is temporary. It runs and is gone,
along with any input typed in, and any output
generated. - Permanent storage is not forever.
5
6File I/O (1 of 5)
- When a program takes data from a file, we say the
program is reading from the file. - When a program sends output to a file, we say the
program is writing to the file. - In C a stream is a special kind of variable
known as an object. (Objects later.) - cin and cout are objects predefined in the
iostream library. - File streams, like other variables, must be
declared by the programmer as needed.
6
7File I/O (2 of 5)
- The include goes in the normal position at the
top of the file. - Example
- include ltfstreamgt
- . . .
- ifstream in_stream
- ofstream out_stream
- These variables are not yet attached to a file,
so are not usable. - The fstream library provides a member function
named open that ties the stream to a file the
outside world knows about. (More later on members
of an object.) - Example
- in_stream.open (infile.dat) //
infile.dat must exist out_stream.open
(outfile.dat) // outfile.dat will be created.
Two new code lines need to be embedded in the
block of a function.
7
8File I/O (3 of 5)
- WORDS OF WARNING
- In the example
- in_stream.open (infile.dat) //
infile.dat must exist on your system - out_stream.open (outfile.dat) //
outfile.dat will be created -
- Depending on your system, you may be limited in
regard to file name length. Many systems require
at most 8 characters for the name and 3
characters for the extension. More recent systems
allow long file names. Read your manuals and ask
a local expert. - The file name arguments for open is known as the
external name for the file. This name must be a
legitimate file name on the system you are using.
The stream name is the name of the file in your
program. - If you have a file named outfile.dat on your
system, and open a file named the same,
outfile.dat. in a program, the program will
delete the old outfile.dat and replace it with
data from your program.
8
9File I/O (4 of 5)
- Once we have declared the file variables,
in_stream and out_stream, and connected them to
files on our system, we can then take input from
in_stream and send output to out_stream in
exactly the same manner as we have for cin and
cout. - Examples
- include ltfstreamgt
- . . .
- // appropriate declarations and open statements
- int one_number, another_number
- in_stream gtgt one_number gtgt another_number
- . . .
- out_stream ltlt one_number ltlt one_number
- ltlt another_number ltlt
another_number
9
10File I/O (5 of 5)
- Every file should be closed when your program is
through fetching input or sending output to the
file. - This is done with the close() function.
- Example
- in_stream.close()
- out_stream.close()
- Note that the close function takes no arguments.
- If your program terminates normally, the system
will close the arguments. - If the program does not terminate normally, this
might not happen. - File corruption is a real possibility.
- If you want to save output in a file and read it
later, the you must close the file before opening
it the second time for reading.
10
11A File Has Two Names
- Every input and every output file in a program
has two names. - The external file name is the real name of the
file, which is the name known to the system. It
is only used in your program in the call to the
open function. - The stream name is the name declared in the
program, and that is tied to the external file
name with the open statement. - After the call to open, the program always uses
the stream name to access the file.
12Introduction to Classes and Objects
- Consider the code fragment
- include ltfstreamgt
- . . .
- ifstream in_stream
- ostream out_stream
- in_stream.open (infile.dat)
- out_stream.open (outfile.dat)
- . . .
- in_stream.close()
- out_stream. close()
- Here the streams in_stream and out_stream are
objects. - An object is a variable that has functions as
well as data associated with it. - The functions open and close are associated with
in_stream and out_stream, as well as the stream
data and file data.
12
13Introduction to Classes and Objects (cont)
- Consider the code fragment
- include ltfstreamgt
- . . .
- ifstream in_stream
- ostream out_stream
- in_stream.open (infile.dat)
- out_stream.open (outfile.dat)
- . . .
- in_stream.close()
- out_stream. close()
- The functions and data associated with an object
are refered to as members of the object. - Functions associated with the object are called
member functions. - Data associated with the object are called data
members. - Note that data members are not (usually)
accessible to functions that arent members.
(More on this later.)
13
14Summary of Classes and Objects
- An object is a variable that has functions
associated with it. - Functions associated with an object are called
member functions. - A class is a type whose variables are objects.
- The objects class determines which member
functions the object has. - Syntax for calling a member function
-
Calling_Object.member_function(Argument_List) - Examples dot operator
- in_stream.open(infile.dat)
- out_stream.open(outfile.dat)
- out_stream.precision(2)
- The meaning of the Member_Function_Name is
determined by the class (type of) the
Calling_Object.
14
15 Programming TipChecking that a file was
opened successfully
- A very common error is attempting to open a file
for reading where the file does not exist. The
member function open fails then. - Your program must test for this failure, and in
the event of failure, manage the error. - Use the istream member function fail to test for
open failure. - in_stream.fail()
- This function returns a bool value that is
true if the stream is in a fail state, and false
otherwise. - Example
- include ltcstdlibgt // for the predefined
exit(1) library function - . . .
- in_stream.open(infile.dat)
- if(in_stream.fail())
-
- cout ltlt Input file opening failed. \n
- exit(1) // Predefined function quits the
program. -
-
15
Note, this can be any number, but 1 is usually
used to indicate an error occurred.
16The exit Statement
- include ltcstdlibgt // exit is defined
here - using namespace std // to gain access to the
names - exit(integer_value) // to exit the
program - When the exit statement is executed, the program
ends immediately. - By convention, 1 is used as an argument for
exit() to signal an error. - By convention, 0 is used to signal a normal
successful completion of the program. (Use of
other values is implementation defined.) - The exit is defined in the cstdlib library header
file, so any use requires - include ltcstdlibgt
- and a directive to gain access to the names
17Display 5.2 File I/O with Checks on open (1 of 2)
- //Reads three numbers from the file
- // infile.dat, sums them, writes the
- // sum to the file outfile.dat.
- include ltfstreamgt
- include ltiostreamgt
- include ltcstdlibgt
- int main( )
-
- using namespace std
- ifstream in_stream
- ofstream out_stream
- in_stream.open("infile.dat")
- if (in_stream.fail( ))
-
- cout ltlt "Input file opening "
- ltlt " failed.\n"
- exit(1)
-
- if (out_stream.fail( ))
-
- cout ltlt "Output file opening failed.\n"
- exit(1)
-
- int first, second, third
- in_stream gtgt first gtgt second gtgt third
- out_stream ltlt "The sum of the first 3\n"
- ltlt "numbers in infile.dat\n"
- ltlt "is " ltlt (first second
third) - ltlt endl
- in_stream.close( )
- out_stream.close( )
- return 0
- //end main
Needed for using files
Needed for cin and cout
Verifies that outfile.dat opened successfully
Needed for using exit(1)
Variable declarations
Gets three integers from the external file
infile.dat
Declares file names to be used in the program
Opens external file named infile.dat
Prints this statement (inserting the sum of the
three integers at the end) into the external file
out.dat
Notice a line return is added to the end.
Closes the two files being used
The return is required since this in NOT a void
function.
Verifies that infile.dat opened successfully
Opens (or creates) external file named outfile.dat
18Summary of File I/O Statements (1 of 3)
These slides are included for you to review the
previous code.
- Input in this code comes from a file with the
directory name infile.dat and output goes to a
file outfile.dat - Put the following include directive in your
program file - include ltfstreamgt // for file i/o
- include ltiostreamgt // for
screen/keyboard i/o - include ltcstdlibgt // for exit
- Choose a stream name for the input the stream,
such as in_stream. Declare it to be a variable of
type ifstream - using namespace std
- ifstream in_stream
- ofstream out_stream
18
19Summary of File I/O Statements (2 of 3)
- Connect each stream to a file using the open
member function with external file name as
argument. Always use the member function fail to
test if the call succeeded. - in_stream.open(infile.dat)
- if (in_streamin.fail())
-
- coutltlt Input file opening failed.\n
- exit(1)
-
- out_stream.open(outfile.dat)
- if(out_stream.fail())
-
- cout ltlt Output file opening failed\n
- exit(1)
-
-
19
20Summary of File I/O Statements (3 of 3)
- Use the stream in_stream to get input from the
file infile.dat just like you use cin input from
the keyboard. - Example
- in_stream gtgt some_variable gtgt
another_variable - Use the stream out_stream to send output to the
file outfile.dat just like you use cout output to
the screen. - Example out_stream ltlt some_variable ltlt
some_variable ltlt endl - Close the streams using the member function
close - in_stream.close()
- out_stream.close()
20
215.2 Tools for Stream I/O
- The layout of your programs output is called the
format of the output. - Facilities are provided in C to control output
format. - Recall this set of commands to provide fixed
point output with two decimal places always
printed - cout .setf(iosfixed)
- cout .setf(iosshowpoint)
- cout.precision(2)
- Replacing cout with an ofstream object allows
formatting of file output - out_stream .setf(iosfixed)
- out_stream .setf(iosshowpoint)
- out_stream.precision(2)
22Formatting Output with Stream Functions
- Every output stream has a member function named
precision. From the point of execution of the
precision member function, the stream output will
be written with either 2 significant figures
total, or 2 places after the decimal, depending
on the setting of the flag for fixed. - The call to precision affects only the calling
stream object. Different output streams may have
different settings.
23Formatting Output with Stream Functions
- cout .setf(iosshowpoint)
- The ostream member function setf sets flags in
the stream. A stream flag is a variable that
controls how the stream behaves. The output
stream has many flags. - The iosshowpoint is a value defined in the
class ios. - Sending the value iosshowpoint to the setf
member function causes the the decimal point
always to be displayed. -
24Formatting Output with Stream Functions
- cout .setf(iosfixed)
- The value iosfixed is another value that may be
passed to the setf member function to set a
corresponding flag in the ostream. - The effect of setting this flag is fixed point
notation. - A number in fixed point does not use the
power-of-ten notation of scientific notation. - Examples
- 10.2423 -5034.6565 0.00011007
- In fact, there is iosscientific to cause that
output style. - Examples
- 1.02423e1 -5.0346565e3 1.1007e-4
25Formatting Output with Stream Functions
- Another useful value is iosshowpos. This value
sets a flat that causes a sign always to be
displayed for positive values. - Examples
- 10.2423 -5034.6565 0.00011007
- 1.2423e10 -5.0346565e3 1.1007e-4
- Weasel words Actually getting this particular
output will require setting several flags.
26Formatting Flags for setf
- Flag value Effect Default
- iosfixed floating output not in not set
- e-notation. Unsets
- scientific flag
- iosscientific floating point output, not set
- will be e-notation as
- needed
- iospos a plus () sign prefixes not set
- all positive output,
- including exponents
- iosshowpoint a decimal point and trailing not
set - zeros are printed for floating
- point output.
27Formatting Flags for setf
- Flag value Effect Default
- iosright if a width is set and output set
- fits within, output is right
- justified within the field
- This flag is cleared by setting
- the right flag.
- iosleft if a width is set and output not set
- fits within, output is left
- justified within the field
- This flag is cleared by setting
- the right flag.
28I/O Manipulators
- An i/o manipulator is a function that is called
in a nonstandard manner. Manipulators are called
by insertion into the output stream as if they
were data. The stream calls the the manipulator
function, changing the state of the i/o stream. - The manipulator setw, with an argument, and the
member function width, with an argument, do the
same thing. - Example The output statement
- cout ltlt Start
- ltlt setw(4) ltlt 10 // Print 10 in a field of
width 4 - ltlt setw(4) ltlt 20 // Print 20 in a field of
width 4 - ltlt setw(6) ltlt 30 // Print 30 in a field of
width 6 - generates the following output (where we have
numbered the - columns)
- Start 10 20 30
- 123456789012345678901
4 sp
4 sp
6 sp
29Display 5.5 Formatting Output (1 of 2)
- //Illustrates output formatting instructions.
- //Reads all the numbers in the file rawdata.dat
and writes the numbers - //to the screen and to the file neat.dat in a
neatly formatted way. - include ltiostreamgt
- include ltfstreamgt
- includeltcstdlibgt
- include ltiomanipgt
- using namespace std
- void make_neat(ifstream messy_file, ofstream
neat_file, - int number_after_decimalpoint, int
field_width) - //Precondition The streams messy_file and
neat_file have been connected - //to files using the function open.
- //Postcondition The numbers in the file
connected to messy_file have been - //written to the screen and to the file connected
to the stream neat_file. - //The numbers are written one per line, in fixed
point notation (i.e., not in - //e-notation), with number_after_decimalpoint
digits after the decimal point - //each number is preceded by a plus or minus sign
and each number is in a field of - //width field_width. (This function does not
close the file.)
Needed to use cout
Needed to use files
Needed to use exit(1)
Needed to use setw
Function prototype
30Formatting Output (2 of 2)
- int main( )
-
- ifstream fin
- ofstream fout
- fin.open("rawdata.dat")
- if (fin.fail( ))
-
- cout ltlt "Input file opening failed.\n"
- exit(1)
-
- fout.open("neat.dat")
- if (fout.fail( ))
-
- cout ltlt "Output file opening failed.\n"
- exit(1)
-
- make_neat(fin, fout, 5, 12)
- //Uses iostream, fstream, and iomanip
- void make_neat(ifstream messy_file, ofstream
neat_file, int number_after_decimalpoint, - int field_width)
-
- neat_file.setf(iosfixed)
- neat_file.setf(iosshowpoint)
- neat_file.setf(iosshowpos)
- neat_file.precision(number_after_decimalpoint)
- cout.setf(iosfixed)
- cout.setf(iosshowpoint)
- cout.setf(iosshowpos)
- cout.precision(number_after_decimalpoint)
- double next
- while (messy_file gtgt next)
-
- cout ltlt setw(field_width) ltlt next ltlt
endl - neat_file ltlt setw(field_width) ltlt next ltlt
endl -
Internal variables for file names
Function receives input file, output file,
requested number of decimal places, and field
width
Open and verify input file
Formats output to outfile
Open and verify output file
Formats output to screen
Function call
While loop continues as until it reaches the end
of the input file
Close 2 files
Takes value from input file and writes it to the
screen in requested format
Takes value from input file and writes it to the
output file in requested format
315.3 Character I/O Member Functions get and put
- C provides low level facilities that input and
output (raw) character data. - The istream member function get reads one
character from the input and stores it in a
variable of type char. - char next_symbol
- cin.get(next_symbol)
- Note that a program can read any character this
way a blank, a newline, or any other character.
31
32Member Functions get and put
- If the code fragment
- char c1, c2, c3, c4, c5 ,c6
- cin.get(c1) cin.get(c2)
- cin.get(c3) cin.get(c4)
- cin.get(c5) cin.get(c6)
- is given input consisting of AB followed by
return then CD followed by return - ABltcrgt
- CDltcrgt
- then the above code fragment sets c1 to A, c2
to B and c3 to \n, that is, c3 is set to the
newline character, c4 is set to C, c5 is set to
D and c6 is set to \n.
32
33Member Functions get and put
- Why would we use get?
- For one thing, your program can detect
end-of-line instead of having the i/o machinery
do it for you. - This loop will let you read a line of input and
stop at the end of a line. Example code - cout ltlt Enter a line of input. I will echo
it\n - char symbol
- do
-
- cin.get(symbol)
- cout ltlt symbol
- while (symbol ! \n)
- cout ltlt That all for this demonstration.\n
33
34Member Function get
- Every input stream has a member function get.
- Syntax
- Input_Stream.get(char_variable)
- Example to read a character from the keyboard
- char next_symbol
- cin.get(next_symbol)
- To read from a file, use a file stream instead of
cin. - In_stream.get(next_symbol)
34
35Member Function put
- Every input stream has a member function put.
- Syntax
- output_Stream.put(char_variable)
- Example to write to the screen
- cin.put(next_symbol)
- cin.put(a)
- To write to a file, use a file stream instead of
cin. - Out_stream.put(next_symbol)
- As with all output, you must declare and connect
your stream to an output file.
35
36\nand \n
- \n and \n seem to be the same thing. They are
NOT the same. Take care to distinguish them. - A cout statement such as
- cout ltlt \n or cout ltlt \n
- will produce the same output flush the output
buffer and write a newline to the output. - HOWEVER
- \n has type char and \n is a cstring literal.
\n has type pointer to char, which you will
study in ACS169. - \n and \n cannot be compared, nor can either
be assigned to a variable of the others type.
36
37The putback Member Function (1 of 2)
- Sometimes you need to inspect but not remove the
next character from the input. You cant really
do this, but you can read the character, decide
you didnt want it, and push it back on the input
stream. - The member function, putback, is a member of
every input stream. It takes an argument type
char, and places the character read from the
input (back) there.
37
38The putback Member Function (2 of 2)
- Example
- fin.get(next)
- while (next ! )
-
- fout.put(next)
- fin.get(next)
-
- fin.putback(next)
- This code reads characters until a blank is
encountered, then puts the blank back on the
input. - A final note The character put back need not
have been read! It can be any character. The
input file will not be changed, but the program
will behave as if it were.
This is a priming read that gets the first
character.
The loop repeats until a space has been found
The character held in next is put into the
outfile.
The next character in the infile is stored in next
The space is returned to the input file
38
39Display 5.6 Checking Input (1 of 2)
- If a program does not check input, a single bad
character input can ruin the entire run of a
program. - This program allows the user to reenter input
until input is satisfactory. - Code
- //Program to demonstrate the functions new_line
and get_input. - include ltiostreamgt
- void new_line( )
- //Discards all the input remaining on the current
input line. - //Also discards the \n at the end of the line.
- //This version only works for input from the
keyboard. - void get_int(int number)
- //Postcondition The variable number has been
- //given a value that the user approves of.
39
40Programming Example (2 of 2)
- int main( )
-
- using namespace std
- int n
- get_int(n)
- cout ltlt "Final value read in " ltlt n
- ltlt endlltlt "End of demonstration.\n"
- return 0
-
- //Uses iostream
- void new_line( )
-
- using namespace std
- char symbol
- do
-
- cin.get(symbol)
//Uses iostream void get_int(int number)
using namespace std char ans do
cout ltlt "Enter input number " cin
gtgt number cout ltlt "You entered " ltlt
number ltlt " Is that correct?
(yes/no) " cin gtgt ans
new_line( ) while ((ans ! 'Y') (ans !
'y'))
Receives variable n as a call-by-reference
parameter and names it number (notice n has no
value at this time)
Function call
Final out put statement is printed on screen and
program ends.
Gets value for number from keyboard
Echoes the enered value for the user to verify
Function call
An easier way to dump the remaining input buffer
is to use cin.ignore(123, \n) instead of this
function This can be used for cin or any in_file.
The number (123) can actually be any integer, but
should be sufficiently large. The \n can be any
delimiter. Basically cin.ignore(123, \n)
ignores the next 123 characters or the newline
(whichever comes first).
Repeats input until user enters something other
than Y or y
The function ends when the user is happy with the
value stored in number
What does this function do???
40
41Pitfall Unexpected \n in Input (1 of 3)
- Example with a problem
- cout ltlt enter a number \n
- int number
- cin gtgt number
- cout ltltenter a letter \n
- char symbol
- cin.get(symbol)
- With the input
- enter a number
- 21
- Enter a letter
- A
- Unfortunately, with this code, the variable
number gets 21, but symbol gets a newline, not
A.
41
42Pitfall Unexpected \n in Input (2 of 3)
- With get, one must account for every character on
the input, even the new-line characters. - A common problem is forgetting to account for the
newline at the ends of every line. - While it is legal to mix cin gtgt style input with
cin.get() input, the code in the previous slide
can cause problems. - You can solve this problem by using the newline()
function from the preceding programming example,
or the .ignore(int, char) function to dump the
characters remaining in the input buffer before
using the .get() function.
42
43Pitfall Unexpected \n in Input (3 of 3)
- Two workable rewrites of the code on prev. slide
1 of 3 - cout ltlt enter a number \n
- int number
- cin gtgt number
- cout ltlt enter a letter \n
- char symbol
- cin gtgt symbol
- You may write
- cout ltlt enter a number \n
- int number
- cin gtgt number
- new_line()
- cout ltlt enter a letter \n
- char symbol
- cin.get(symbol)
A third solution would replace this line
with cin.ignore(123, \n)
43
44The eof Member Function(1 of 2)
- Every input-file stream has a function to detect
end-of-file called eof. The letters stand for end
of file. - This function returns a bool value, true if the
input file is at end-of-file, false otherwise. - The result of this function can be used to
control a while-loop, a for- loop or an if
statement. - Typically, what we are really interested in is
when we are not at end of file. The code usually
reads, - while(! in_stream.eof())
-
- // do something with the in_stream
-
44
45The eof Member Function (2 of 2)
- The while loop might look like this
- in_stream.get(next)
- while(! In_stream.eof())
-
- cout ltlt next // This could be cout.put(next)
- in_stream.get(next) // This read is required!
-
- This loop reads the file attached to in_stream
into the char variable next character by
character. - There is an end of file marker that can be read.
The eof function does not change from false to
true until this marker is read. You can read this
marker but writing it out produces unpredictable
results.
Always use a priming read OUTSIDE the loop!
45
46An Alternate Method for Checking the eof
- while(instream gtgt next)
-
- cout ltlt next
-
- Compared to
- in_stream.get(next)
- while(! In_stream.eof())
-
- cout ltlt next
- in_stream.get(next)
-
This condition replaces the priming read AND
the eof check AND the next read
47Display 5.7Call by Reference parameters (1 of 2)
- //Program to create a file called cplusad.dat
which is identical to the file - //cad.dat, except that all occurrences of C are
replaced by "C". - //Assumes that the uppercase letter C does not
occur in cad.dat, except - //as the name of the C programming language.
- include ltfstreamgt
- include ltiostreamgt
- include ltcstdlibgt
- using namespace std
- void add_plus_plus(ifstream in_stream, ofstream
out_stream) - //Precondition in_stream has been connected to
an input file with open. - //out_stream has been connected to an output file
with open. - //Postcondition The contents of the file
connected to in_stream have been - //copied into the file connected to out_stream,
but with each C replaced - //by "C". (The files are not closed by this
function.)
48Call by Reference parameters (2 of 2)
- int main( )
-
- ifstream fin
- ofstream fout
- cout ltlt "Begin editing files.\n"
- fin.open("cad.dat")
- if (fin.fail( ))
-
- cout ltlt "Input file opening failed.\n"
- exit(1)
-
- fout.open("cplusad.dat")
- if (fout.fail( ))
-
- cout ltlt "Output file opening failed.\n"
- exit(1)
- // int main() continued
- fin.close( )
- fout.close( )
- cout ltlt "End of editing files.\n"
- return 0
-
- void add_plus_plus(ifstream in_stream, ofstream
out_stream) -
- char next
- in_stream.get(next)
- while (! in_stream.eof( ))
-
- if (next 'C')
- out_stream ltlt "C"
- else
- out_stream ltlt next
49Display 5.8 Some predefined character
functions(1 of 2)
- To access these predefined library functions,
your code must contain - include ltcctypegt
- Here is an abbreviated table of functions from
cctype. - Function Description
Example . - toupper(char) if char is lowercase
char c toupper(a) - transform
char to cout ltlt c // writes A - uppercase and return
- else
- return
char - tolower(char_expr) lowercase version of
toupper - isupper(char_expr) if arg is uppercase
char c a - return true
if (isupper(c)) - else return false
cout ltlt Uppercase
49
50Some predefined character functions (2 of 2)
- Function Description Example
. - isalpha(char) if (A lt char char
c - charlt Z
if(isalpha(c)) - a lt char
cout ltlt c ltlt is a letter. - charlt z )
else - return true
cout ltlt c ltlt is not a letter. - else
- return false
- isdigit(char) if (0 lt char
charlt 0) if (isdigit(c)) - return true cout ltlt c ltlt is
a digit. - else else
- return false cout ltlt c ltlt is
not a digit. -
- isspace(char) if (charis any
whitespace, - such as tab, newline or blank)
-
return true - else
-
return false
50
515.4 Inheritance
- One of the most powerful features of C is the
use of derived classes. - A class is derived from another class, means that
the derived class is obtained from the first
class by adding features while retaining all the
features in the first class. - We speak of the first class as the base class.
- We speak of the derived class inheriting from the
base class, and refer to this mechanism as
inheritance.
51
52Inheritance Among Stream Classes (1 of 2)
- Recall that an object has data and functions.
- Recall further that a class is a type whose
variables are objects. - It turns out that file streams (members of
fstream) are derived from the iostream class. - In particular, ifstream inherits from istream,
and ofstream inherits from ostream. - Notice that ifstream has the open() member
function but istream does not. - Recall that an object has associated data and
functions. - A class is a type whose variables are objects.
52
53Inheritance Among Stream Classes (2 of 2)
- If class D inherits from class B, then B is said
to be the base class, and D is said to be the
derived class. - If class D inherits from class B, then any object
of class D is also an object of class B. Wherever
a class B object is used, we can substitute it by
a class D object. - If class D inherits from class B, then class B is
called the parent class and class D is called the
child class. - You will see the words superclass used for base
class and subclass used for derived class.
Stroustrup, the designer of C, finds idea that
a subclass has more features than the superclass
to be counter-intuitive. We weigh in against this
usage. These terms are used in several OO
languages such as Smalltalk, Java and CLOS. We
prefer base class and derived class.
53
54Making Stream Parameters Versatile
- Suppose you define a function that takes a input
stream as an argument and you want the argument
to be cin in some cases and an input-file stream
in others. To accomplish this, you can use
istream as a formal parameter type. Then you can
use either an ifstream object or an istream
object (cin) as the argument. - Similarly, you can define a function that uses an
ostream formal parameter then use either an
ofstream object or cout as the argument.
54
55Another new_line function
- By using an istream formal parameter, we can use
this new_line function with either ifstream or
istream arguments. - //Uses iostream
- void new_line(istream ins)
-
- char symbol
- do
-
- ins.get(symbol)
- while (symbol ! \n)
The call could be either new_line(cin) or new_lin
e(in_file)
55
56Default Arguments (1 of 2)
- An alternative to writing two version of
new_line() we can write one version with a
default argument - //Uses iostream
- void new_line(istream ins cin)
-
- char symbol
- do
-
- ins.get(symbol)
- while (symbol ! \n)
-
The call could now be new_line() //defaults to
cin or new_line(in_file)
56
57Default Arguments (2 of 2)
- If a function has several parameters and some of
those tend to be consistent, the consistent
parameters can be set using default arguments. - However, any parameters assigned default
parameters must appear at the end of the
parameter list. - In the call, arguments are plugged in for
parameters in the order given and any missing
arguments are assigned their respective default
value. - Consider this function header
- void my_func(int num1, double num2 5.0, int
num3 4) - Then the following calls are possible
- my_func(num) //assigns num1 the value of num
- // and accepts the default values for num2 and
num3. - my_func(num, avg) //assigns num1 the value of
num, - // and num2 the value of avg and accepts the
default for num3 - Note It is not possible to send a value for num3
without also sending a value for num2!
57
58Summary(1 of 3)
- A stream of type ifstream can be connected to a
file with the open member function. The program
can then take input from the file connected to
the stream. - A stream of type ofstream can be connected to a
file with the open member function. The program
can then send output to the file connected to the
stream. - Always use the .fail() member function to check
success in opening a file. - A object is a variable that has functions and
data associated with it. - A class is a type whose variables are objects.
The class determines the associated functions and
data. - Syntax for calling a member function of an
object - calling_object.member_function_name(Argument_list
) - Example cout.precision(4)
58
59Summary(2 of 3)
- Stream member functions such as width, setf, and
precision, can be used to format output. These
member functions work for cout and for ofstream
objects. - Stream type formal parameters must be reference
parameters. - If the formal parameter is of type istream, the
corresponding argument may be either of type
istream or ifstream. - Every input stream has a member function named
get that reads one character at a time. There is
a corresponding member function named put that
writes one character to the output stream. - The member function eof can be used to determine
whether the the program has reached the end of
the input file. (You can also use the alternative
method.)
59
60Summary(3 of 3)
- C provides for default arguments that provide
values for parameters if the corresponding
argument in a call are omitted. These arguments
must follow any parameters that are not provided
default arguments. Calls to such a function must
provide arguments for parameters without default
arguments first. Arguments beyond this replace
default arguments up to the number of parameters
the function has.
60