0% found this document useful (0 votes)
42 views107 pages

Ses11 Fstream

This document provides an overview of streams and basic file input/output (I/O) in C++. It discusses how streams represent a flow of data into and out of a program. Streams can be connected to keyboards, screens, or files for input and output. The cin and cout streams are predefined to accept input from the keyboard and provide output to the screen. File streams like ifstream and ofstream can be declared and used to read from and write to files. Opening a file connects the stream to the file, while closing disconnects it. Streams are objects that have member functions like open() that perform tasks related to files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views107 pages

Ses11 Fstream

This document provides an overview of streams and basic file input/output (I/O) in C++. It discusses how streams represent a flow of data into and out of a program. Streams can be connected to keyboards, screens, or files for input and output. The cin and cout streams are predefined to accept input from the keyboard and provide output to the screen. File streams like ifstream and ofstream can be declared and used to read from and write to files. Opening a file connects the stream to the file, while closing disconnects it. Streams are objects that have member functions like open() that perform tasks related to files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

II

I/O Streams as an Introduction to Objects


and Classes
Overview

1 Streams and Basic File I/O

2 Tools for Stream I/O

3 Character I/O

4 Inheritance
Slide 6- 2
1
Streams and Basic File I/O
I/O Streams
n I/O refers to program input and output
n Input is delivered to your program via a stream object

n Input can be from

n The keyboard
n A file

n Output is delivered to the output device via a stream


object
n Output can be to

n The screen
n A file
Slide 6- 4
Objects

n Objects are special variables that


n Have their own special-purpose functions

n Set C++ apart from earlier programming languages

Slide 6- 5
Streams and Basic File I/O
n Files for I/O are the same type of files used to
store programs
n A stream is a flow of data.
n Input stream: Data flows into the program

n If input stream flows from keyboard, the program will


accept data from the keyboard
n If input stream flows from a file, the program will accept

data from the file


n Output stream: Data flows out of the program
n To the screen
n To a file Slide 6- 6
cin And cout Streams
n cin
n Input stream connected to the keyboard

n cout
n Output stream connected to the screen

n cin and cout defined in the iostream library


n Use include directive: #include <iostream>

n You can declare your own streams to use with


files.

Slide 6- 7
Why Use Files?

n Files allow you to store data permanently!


n Data output to a file lasts after the program ends
n An input file can be used over and over
n No typing of data again and again for testing

n Create a data file or read an output file at your


convenience
n Files allow you to deal with larger data sets

Slide 6- 8
File I/O
n Reading from a file
n Taking input from a file

n Done from beginning to the end (for now)

n No backing up to read something again (OK to start over)


n Just as done from the keyboard

n Writing to a file
n Sending output to a file

n Done from beginning to end (for now)

n No backing up to write something again( OK to start over)


n Just as done to the screen
Slide 6- 9
Stream Variables

n Like other variables, a stream variable…


n Must be declared before it can be used

n Must be initialized before it contains valid data

n Initializing a stream means connecting it to a file


n The value of the stream variable can be thought of
as the file it is connected to
n Can have its value changed
n Changing a stream value means disconnecting from one file and
connecting to another

Slide 6- 10
Streams and Assignment

n A stream is a special kind of variable called


an object
n Objects can use special functions to complete tasks

n Streams use special functions instead of the


assignment operator to change values

Slide 6- 11
Declaring An
Input-file Stream Variable

n Input-file streams are of type ifstream

n Type ifstream is defined in the fstream library


n You must use the include and using directives

#include <fstream>
using namespace std;

n Declare an input-file stream variable using


ifstream in_stream;
Slide 6- 12
Declaring An
Output-file Stream Variable

n Ouput-file streams of are type ofstream


n Type ofstream is defined in the fstream library
n You must use these include and using directives

#include <fstream>
using namespace std;

n Declare an input-file stream variable using


ofstream out_stream;

Slide 6- 13
Connecting To A File
n Once a stream variable is declared, connect it to
a file
n Connecting a stream to a file is opening the file

n Use the open function of the stream object

in_stream.open("infile.dat");

Double quotes
Period
Slide 6- 14
Using The Input Stream

n Once connected to a file, the input-stream


variable can be used to produce input just as
you would use cin with the extraction operator
n Example:
int one_number, another_number;
in_stream >> one_number
>> another_number;

Slide 6- 15
Using The Output Stream
n An output-stream works similarly to the
input-stream
n ofstream out_stream;
out_stream.open("outfile.dat");

out_stream << "one number = "


<< one_number
<< "another number = "
<< another_number;

Slide 6- 16
External File Names

n An External File Name…


n Is the name for a file that the operating system uses

n infile.dat and outfile.dat used in the previous examples


n Is the "real", on-the-disk, name for a file
n Needs to match the naming conventions on

your system
n Usually only used in the stream's open statement

n Once open, referred to using the

name of the stream connected to it.


Slide 6- 17
Closing a File

n After using a file, it should be closed


n This disconnects the stream from the file

n Close files to reduce the chance of a file being

corrupted if the program terminates abnormally


n It is important to close an output file if your
program later needs to read input from the output file
n The system will automatically close files if you
forget as long as your program ends normally

Slide 6- 18
Objects
n An object is a variable that has functions and
data associated with it
n in_stream and out_stream each have a function named open
associated with them
n in_stream and out_stream use different
versions of a function named open
n One version of open is for input files
n A different version of open is for output files

Slide 6- 19
Member Functions

n A member function is a function associated with


an object
n The open function is a member function of

in_stream in the previous examples


n A different open function is a member function of out_stream in

the previous examples

Slide 6- 20
Objects and
Member Function Names

n Objects of different types have different member


functions
n Some of these member functions might have the same

name

n Different objects of the same type have the same


member functions

Slide 6- 21
Classes

n A type whose variables are objects, is a class


n ifstream is the type of the in_stream variable (object)

n ifstream is a class

n The class of an object determines its

member functions
n Example:

ifstream in_stream1, in_stream2;


n in_stream1.open and in_stream2.open are the same
function but might have different arguments
Slide 6- 22
Class Member Functions

n Member functions of an object are the member


functions of its class
n The class determines the member functions of
the object
n The class ifstream has an open function

n Every variable (object) declared of type ifstream

has that open function

Slide 6- 23
Calling a Member Function

n Calling a member function requires specifying


the object containing the function
n The calling object is separated from the member
function by the dot operator
n Example: in_stream.open("infile.dat");

Calling object Member function


Dot operator
Slide 6- 24
Member Function
Calling Syntax

n Syntax for calling a member function:

Calling_object .Member_Function_Name(Argument_list);

Slide 6- 25
Errors On Opening Files

n Opening a file could fail for several reasons


n Common reasons for open to fail include

n The file might not exist


n The name might be typed incorrectly

n May be no error message if the call to open fails


n Program execution continues!

Slide 6- 26
Catching Stream Errors

n Member function fail, can be used to test the


success of a stream operation
n fail returns a boolean type (true or false)

n fail returns true if the stream operation failed

Slide 6- 27
Halting Execution

n When a stream open function fails, it is


generally best to stop the program
n The function exit, halts a program
n exit returns its argument to the operating system

n exit causes program execution to stop

n exit is NOT a member function

n Exit requires the include and using directives


#include <cstdlib>
using namespace std;
Slide 6- 28
Using fail and exit

n Immediately following the call to open, check


that the operation was successful:

in_stream.open("stuff.dat");
if( in_stream.fail( ) )
{
cout << "Input file opening failed.\n";
exit(1) ;
}
Slide 6- 29
Techniques for File I/O
n When reading input from a file…
n Do not include prompts or echo the input

n The lines cout << "Enter the number: ";


cin >> the_number;
cout << "The number you entered is "
<< the_number;
become just one line

in_file >> the_number;

n The input file must contain exactly the data expected


Slide 6- 30
Appending Data (optional)

n Output examples so far create new files


n If the output file already contains data, that data

is lost
n To append new output to the end an existing file
n use the constant ios::app defined in the iostream

library:
outStream.open("important.txt", ios::app);

n If the file does not exist, a new file will be created


Slide 6- 31
Slide 6- 32
File Names as Input (optional)

n Program users can enter the name of a file to


use for input or for output
n Program must use a variable that can hold
multiple characters
n A sequence of characters is called a string

n Declaring a variable to hold a string of characters:


char file_name[16];
n file_name is the name of a variable
n Brackets enclose the maximum number of characters + 1

n The variable file_name contains up to 15 characters

Slide 6- 33
Using A Character String

n char file_name[16];
cout << "Enter the file_name ";
cin >> file_name;
ifstream in_stream;
in_stream.open(file_name);
if (in_stream.fail( ) )
{
cout << "Input file opening failed.\n";
exit(1);
}
Slide 6- 34
Conclusion
n Can you
n Write a program that uses a stream called fin which

will be connected to an input file and a stream called


fout which will be connected to an output file? How
do you declare fin and fout? What include
directive, if any, do you nee to place in your
program file?
n Name at least three member functions of an

iostream object and give examples of usage of


each?
Slide 6- 35
2
Tools for Streams I/O
Tools for Stream I/O
n To control the format of the program's output
n We use commands that determine such details as:

n The spaces between items


n The number of digits after a decimal point
n The numeric style: scientific notation for fixed point
n Showing digits after a decimal point even if they are zeroes
n Showing plus signs in front of positive numbers
n Left or right justifying numbers in a given space

Slide 6- 37
Formatting Output to Files

n Format output to the screen with:


cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

n Format output to a file using the out-file stream


named out_stream with:
out_stream.setf(ios::fixed);
out_stream.setf(ios::showpoint);
out_stream.precision(2); Slide 6- 38
out_stream.precision(2);

n precision is a member function of output streams


n After out_stream.precision(2);

Output of numbers with decimal points…


n will show a total of 2 significant digits
23. 2.2e7 2.2 6.9e-1 0.00069
OR
n will show 2 digits after the decimal point

23.56 2.26e7 2.21 0.69 0.69e-4


n Calls to precision apply only to the stream
named in the call
Slide 6- 39
setf(ios::fixed);

n setf is a member function of output streams


n setf is an abbreviation for set flags

n A flag is an instruction to do one of two options


n ios::fixed is a flag

n After out_stream.setf(ios::fixed);
All further output of floating point numbers…
n Will be written in fixed-point notation, the way we
normally expect to see numbers
n Calls to setf apply only to the stream named in
the call Slide 6- 40
setf(ios::showpoint);

n After out_stream.setf(ios::showpoint);

Output of floating point numbers…


n Will show the decimal point even if all digits after the
decimal point are zeroes

Slide 6- 41
Slide 6- 42
Creating Space in Output

n The width function specifies the number of


spaces for the next item
n Applies only to the next item of output

n Example: To print the digit 7 in four spaces use


out_stream.width(4);
out_stream << 7 << endl;
n Three of the spaces will be blank

7 7
Slide 6- 43
Not Enough Width?

n What if the argument for width is too small?


n Such as specifying

cout.width(3);
when the value to print is 3456.45
n The entire item is always output
n If too few spaces are specified, as many more

spaces as needed are used

Slide 6- 44
Unsetting Flags

n Any flag that is set, may be unset


n Use the unsetf function
n Example:

cout.unsetf(ios::showpos);

causes the program to stop printing plus signs on positive


numbers

Slide 6- 45
Manipulators

n A manipulator is a function called in a


nontraditional way
n Manipulators in turn call member functions

n Manipulators may or may not have arguments

n Used after the insertion operator (<<) as if the

manipulator function call is an output item

Slide 6- 46
The setw Manipulator

n setw does the same task as the member


function width
n setw calls the width function to set spaces for output

n Example: cout << "Start" << setw(4) << 10


<< setw(4) << setw(6) << 30;

produces: Start 10 20 30

Two Spaces Four Spaces


Slide 6- 47
The setprecision Manipulator
n setprecision does the same task as the member
function precision

n Example: cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout << "$" << setprecision(2)
<< 10.3 << endl
<< "$" << 20.5 << endl;

produces: $10.30
$20.50
n setprecision setting stays in effect until changed Slide 6- 48
Manipulator Definitions

n The manipulators setw and setprecision are


defined in the iomanip library
n To use these manipulators, add these lines

#include <iomanip>
using namespace std;

Slide 6- 49
Stream Names as Arguments

n Streams can be arguments to a function


n The function's formal parameter for the stream

must be call-by-reference

n Example: void make_neat(ifstream& messy_file,


ofstream& neat_file);

Slide 6- 50
The End of The File

n Input files used by a program may vary in length


n Programs may not be able to assume the number

of items in the file


n A way to know the end of the file is reached:
n The boolean expression (in_stream >> next)

n Reads a value from in_stream and stores it in next


n True if a value can be read and stored in next

n False if there is not a value to be read (the end of the file)

Slide 6- 51
End of File Example
n To calculate the average of the numbers in a file
n double next, sum = 0;
int count = 0;
while(in_stream >> next)
{
sum = sum + next;
count++;
}

double average = sum / count;

Slide 6- 52
Stream Arguments
and Namespaces
n Using directives have been local to function
definitions in the examples so far
n When parameter type names are in a namespace
n A using directive must be outside the function so

C++ will understand the parameter type names such


as ifstream
n Easy solution is to place the using directive at the
beginning of the file
n Many experts do not approve as this does not allow

using multiple namespaces with names in common


Slide 6- 53
Program Example

n The program in Display 6.6…


n Takes input from rawdata.dat

n Writes output to the screen and to neat.dat

n Formatting instructions are used to create a neater layout


n Numbers are written one per line in a field width of 12

n Each number is written with 5 digits after the decimal point

n Each number is written with a plus or minus sign

n Uses function make_neat that has formal parameters


for the input-file stream and output-file stream
Slide 6- 54
Slide 6- 55
Slide 6- 56
Slide 6- 57
Conclusion
n Can you
n Show the output produced when the following line
is executed?

cout << "*" << setw(3) << 12345 << "*" endl;

n Describe the effect of each of these flags?


Ios::fixed ios::scientific ios::showpoint
ios::right ios::right ios::showpos

Slide 6- 58
3
Character I/O
Character I/O

n All data is input and output as characters


n Output of the number 10 is two characters '1' and '0'

n Input of the number 10 is also done as '1' and '0'

n Interpretation of 10 as the number 10 or as characters

depends on the program


n Conversion between characters and numbers is

usually automatic

Slide 6- 60
Low Level Character I/O

n Low level C++ functions for character I/O


n Perform character input and output

n Do not perform automatic conversions

n Allow you to do input and output in anyway you

can devise

Slide 6- 61
Member Function get

n Function get
n Member function of every input stream

n Reads one character from an input stream

n Stores the character read in a variable of type char, the single

argument the function takes


n Does not use the extraction operator (>>)

which performs some automatic work


n Does not skip blanks

Slide 6- 62
Using get

n These lines use get to read a character and store


it in the variable next_symbol

char next_symbol;
cin.get(next_symbol);

n Any character will be read with these statements


n Blank spaces too!
n '\n' too! (The newline character)

Slide 6- 63
get Syntax

n input_stream.get(char_variable);

n Examples: char next_symbol;


cin.get(next_symbol);

ifstream in_stream;
in_stream.open("infile.dat");
in_stream.get(next_symbol);

Slide 6- 64
More About get
n Given this code: char c1, c2, c3;
cin.get(c1);
cin.get(c2);
cin.get(c3);
and this input:
AB
CD
n c1 = 'A' c2 = 'B' c3 = '\n'
n cin >> c1 >> c2 >> c3; would place 'C' in c3
(the ">>" operator skips the newline character)

Slide 6- 65
The End of The Line
n To read and echo a line of input
n Look for '\n' at the end of the input line:
cout<<"Enter a line of input and I will "
<< "echo it.\n";
char symbol;
do
{
cin.get(symbol);
cout << symbol;
} while (symbol != '\n');
n All characters, including '\n' will be output

Slide 6- 66
'\n ' vs "\n "
n '\n'
n A value of type char

n Can be stored in a variable of type char

n "\n"
n A string containing only one character

n Cannot be stored in a variable of type char

n In a cout-statement they produce the same result

Slide 6- 67
Member Function put

n Function put
n Member function of every output stream

n Requires one argument of type char

n Places its argument of type char in the output stream

n Does not do allow you to do more than previous output with the

insertion operator and cout

Slide 6- 68
put Syntax
n Output_stream.put(Char_expression);

n Examples: cout.put(next_symbol);
cout.put('a');

ofstream out_stream;
out_stream.open("outfile.dat");
out_stream.put('Z');

Slide 6- 69
Member Function putback

n The putback member function places a character


in the input stream
n putback is a member function of every input stream

n Useful when input continues until a specific character

is read, but you do not want to process the character


n Places its argument of type char in the input stream

n Character placed in the stream does not have to

be a character read from the stream

Slide 6- 70
putback Example
n The following code reads up to the first blank in
the input stream fin, and writes the characters to
the file connected to the output stream fout
n fin.get(next);
while (next != ' ')
{
fout.put(next);
fin.get(next);
}
fin.putback(next);
n The blank space read to end the loop is put back into
the input stream Slide 6- 71
Program Example
Checking Input
n Incorrect input can produce worthless output

n Use input functions that allow the user to


re-enter input until it is correct, such as
n Echoing the input and asking the user if it is correct

n If the input is not correct, allow the user to enter the data again

Slide 6- 72
Checking Input:
get_int

n The get_int function seen in Display 6.7


obtains an integer value from the user
n get_int prompts the user, reads the input, and displays

the input
n After displaying the input, get_int asks the user to

confirm the number and reads the user's response


using a variable of type character
n The process is repeated until the user indicates with

a 'Y' or 'y' that the number entered is correct


Slide 6- 73
Mixing cin >> and cin.get

n Be sure to deal with the '\n' that ends each


input line if using cin >> and cin.get
n "cin >>" reads up to the '\n'

n The '\n' remains in the input stream

n Using cin.get next will read the '\n'

Slide 6- 74
'\n' Example
The Dialogue:
n The Code: Enter a number:
cout << "Enter a number:\n"; 21
int number; Now enter a letter:
cin >> number;
A
cout << "Now enter a letter:\n";
char symbol; The Result:
cin.get(symbol);
number = 21
symbol = '\n'
Slide 6- 75
A Fix To Remove '\n'

n cout << "Enter a number:\n";


int number;
cin >> number;
cout << "Now enter a letter:\n";
char symbol;
cin >>symbol;

Slide 6- 76
Another '\n' Fix

n cout << "Enter a number:\n";


int number;
cin >> number;
new_line( ); //
cout << "Now enter a letter:\n";
char symbol;
cin.get(symbol);

Slide 6- 77
Detecting the End of a File
n Member function eof detects the end of a file
n Member function of every input-file stream

n eof stands for end of file

n eof returns a boolean value

n True when the end of the file has been reached


n False when there is more data to read
n Normally used to determine when we are NOT
at the end of the file
n Example: if ( ! in_stream.eof( ) )

Slide 6- 78
Using eof

n This loop reads each character, and writes it to


the screen
n in_stream.get(next);
while (! in_stream.eof( ) )
{
cout << next;
in_stream.get(next);
}
n ( ! In_stream.eof( ) ) becomes false when the
program reads past the last character in the file Slide 6- 79
The End Of File Character

n End of a file is indicated by a special character


n in_stream.eof( ) is still true after the last
character of data is read
n in_stream.eof( ) becomes false when the
special end of file character is read

Slide 6- 80
How To Test End of File

n We have seen two methods


n while ( in_stream >> next)

n while ( ! in_stream.eof( ) )

n Which should be used?


n In general, use eof when input is treated as text and using a

member function get to read input


n In general, use the extraction operator method when processing

numeric data

Slide 6- 81
Program Example:
Editing a Text File

n The program of Display 6.8…


n Reads every character of file cad.dat and copies it to

file cplusad.dat except that every 'C' is changed to


"C++" in cplusad.dat
n Preserves line breaks in cad.dat

n get is used for input as the extraction operator would skip


line breaks
n get is used to preserve spaces as well

n Uses eof to test for end of file


Slide 6- 82
Character Functions

n Several predefined functions exist to facilitate


working with characters

n The cctype library is required


n #include <cctype>
using namespace std;

Slide 6- 83
The toupper Function

n toupper returns the argument's upper case


character
n toupper('a') returns 'A'

n toupper('A') return 'A'

Slide 6- 84
toupper Returns An int

n Characters are actually stored as an integer


assigned to the character
n toupper and tolower actually return the integer
representing the character
n cout << toupper('a'); //prints the integer for 'A'
n char c = toupper('a'); //places the integer for 'A' in c

cout << c; //prints 'A'


n cout << static_cast<char>(toupper('a')); //works too

Slide 6- 85
The isspace Function

n isspace returns true if the argument is whitespace


n Whitespace is spaces, tabs, and newlines

n isspace(' ') returns true

n Example: if (isspace(next) )
cout << '-';
else
cout << next;
n Prints a '-' if next contains a space, tab, or
newline character
n See more character functions in
Slide 6- 86
Slide 6- 87
Slide 6- 88
Conclusion

n Can you
n Write code that will read a line of text and echo the line with all

the uppercase letters deleted?

n Describe two methods to detect the end of an input file:

n Describe whitespace?

Slide 6- 89
4
Inheritance
Inheritance

n Inheritance refers to derived classes


n Derived classes are obtained from another class

by adding features
n The class of input-file streams is derived from the

class of all input streams by adding member


functions such as open and close
n cin belongs to the class of all input streams, but not

the class of input-file streams

Slide 6- 91
Inheritance and Streams

n cin and an input-file stream are input streams


n Input-file streams are members of the class ifstream

n Can be connected to a file


n cin is a member of the class istream (no 'f ')
n Cannot be connected to a file
n The ifstream class is a derived class of the
istream class

Slide 6- 92
Stream Parameters Review
n Example:
void two_sum(ifstream& source_file)
{
int n1, n2;
source_file >> n1 >> n2;
cout << n1 " + " << n2
<< " = " << (n1 + n2) << endl;
}
n This code could be called using
ifstream fin;
fin.open("input.dat");
two_sum (fin);
Slide 6- 93
two_sum Is Not Versatile
n Suppose you wished to use function two_sum
with cin
n Since cin and input-file streams are both input
streams, this call to two_sum seems to make sense:

two_sum(cin);

but it will not work!

Slide 6- 94
Fixing two_sum

n This version of two_sum works with cin:


void better_two_sum(istream& source_file)
{
int n1, n2;
source_file >> n1 >> n2;
cout << n1 " + " << n2
<< " = " << (n1 + n2) << endl;
}

n better_two_sum can be called with:


better_two_sum(cin); Slide 6- 95
Derived Classes and Parameters
n better_two_sum can also be called with:
ifstream fin;
fin.open("input.dat");
better_two_sum(fin);
n fin is of two types
n fin is an input-file stream

n fin is also of type istream

n fin has all the features of the input stream class,


plus added capabilities
n A formal parameter of type istream can be replaced by
an argument of type ifstream
Slide 6- 96
Derived Class Arguments

n A restriction exists when using derived classes


as arguments to functions
n A formal parameter of type istream, can only use

member functions of the istream class


n Using an argument of type ifstream with a formal

parameter of type istream does not allow using


the open and close methods of the ifstream class!
n Open files before calling the function
n Close files after calling the function

Slide 6- 97
Inheritance Relationships

n If class B is derived from class A


n Class B is a derived class of class A

n Class B is a child of class A

n Class A is the parent of class B

n Class B inherits the member functions of class A

Slide 6- 98
Inheritance and Output
n ostream is the class of all output streams
n cout is of type ostream

n ofstream is the class of output-file streams


n The ofstream class is a child class of ostream

n This function can be called with ostream or


ofstream arguments
void say_hello(ostream& any_out_stream)
{
any_out_stream << "Hello";
}

Slide 6- 99
Program Example:
Another new_line Function

n The new_line function from Display 6.7 only


works with cin
n This version works for any input stream
void new_line(istream& in_stream)
{
char symbol;
do
{
in_stream.get(symbol);
}while (symbol != '\n');
} Slide 6- 100
Slide 6- 101
Program Example:
Calling new_line

n The new version of new_line can be called with


cin as the argument
new_line(cin);
n If the original version of new_line is kept in the

program, this call produces the same result


new_line( );
n New_line can also be called with an
input-file stream as an argument
new_line(fin);
Slide 6- 102
Default Arguments
n It is not necessary to have two versions of
the new_line function
n A default value can be specified in the parameter list

n The default value is selected if no argument is


available for the parameter
n The new_line header can be written as
new_line (istream & in_stream = cin)
n If new_line is called without an argument, cin is used

Slide 6- 103
Multiple Default Arguments

n When some formal parameters have default


values and others do not
n All formal parameters with default values must be

at the end of the parameter list


n Arguments are applied to the all formal parameters

in order just as we have seen before


n The function call must provide at least as many

arguments as there are parameters without default


values
Slide 6- 104
Default Argument Example
n void default_args(int arg1, int arg2 = -3)
{
cout << arg1 << ' ' << arg2 << endl;
}
n default_args can be called with one or
two parameters
n default_args(5); //output is 5 -3
n default_args(5, 6); //output is 5 6

Slide 6- 105
Conclusion

n Can you
n Identify the types of cin and cout?

n Describe how to connect a stream to a file?

n Define object?

n Define class?

n Describe the relationship between parent and child

classes?
n List functions that format output?

n List functions that assist character input and output?

Slide 6- 106
TUTORIAL 5
1. Write a program to print out the source code to the screen.
2. Still that program but to print the source code without comment to a file
no_comment.cpp.
3. Each character is one byte. Calculate the amount of memory in bytes only to
save the code of the program (of course without comment)
4. Print out the source code to the screen in the reverse order.
5. Write a program to read two large integer from file “input”. Calculate sum of the
two integers and print out the result to file “output”. The number of digits in one
integer varies from 1 to 1000000.
Two integers are separated by a space character.

Slide 6- 107

You might also like