You are on page 1of 44

CO1401 / CO1457

Programming

Week 2
Functions & Files
A function example

void my_func()
{
cout << "hello world\n";
}

int main()
{
my_func();
// other things happen
my_func();
}

2 Programming
Program flow

Function
Invoke
function

3 Programming
void Function1( )
{
cout << "Inside function 1" << endl;
}

void Function2( )
{
cout << "Inside function 2" << endl;
}

int main( )
{
Function1();
cout << "inside main" << endl;
Function1();
cout << "inside main" << endl;
Function2();
cout << "inside main" << endl;
}

4 Programming
Example Sequence

Inside function 1
inside main
Inside function 1
inside main
Inside function 2
inside main

5 Programming
• Some functions int main()
just execute useful {
code. clear_screen();
}

• No data is passed to the function clear_screen() and


the function does not pass any data back to the
calling code. The function would look like:
void clear_screen()
{
// do something here
}
6 Programming
Scope

• C++ has "scope" rules.


• Scope means the area of the code in which the variable
can be used.
• It is the area of the program to which the variable is
visible.
• A variable name can be repeated if the scope of the
two names is different.
• Essentially the scope of a variable is the block of code
in which it s declared.
• For a function, the scope of a variable is the function in
which it is declared. A variable declared in one function
is not visible to other functions.

7 Programming
Local Variables

#include <iostream>
using namespace std;

int main()
{
int counter1; // local to main()

// body of main
}

8 Programming
void foo(int number) // local to foo()
{
cout << number;
}

int main()
{
int value = 4;
foo( value )
}

9 Programming
Communication

• This is done using:


• parameters
• the return statement

• Send data to a function using the parameter list.

• Get data back from a function using the return


statement and using reference parameters (later in
lecture).

10 Programming
Area of a square 1

float calcArea()
{
float width = 5.7;
float height = 4.3;
float area;
area = width * height;
return area;
}

int main()
{
cout << "box area is ";
float area = calcArea();
cout << area << "\n";
}
11 Programming
Parameters

• The function is of limited use because it is specific.

• Better to have a general purpose function.

12 Programming
Area of a square 2

//Calculate the area of a square


float CalcArea(float width, float height)
{
float area;
area = width * height;
return area;
}

int main()
{
float area = CalcArea( 32.5, 17.0 );
cout << area << endl
}

13 Programming
Parameters

• The function is flexible because data can be passed to it.

• The parameters written in the function definition are


the formal parameters.

• The parameters supplied used when the function is


invoked are the actual parameters.

• The word arguments is used by some instead of


parameters.

14 Programming
"return"

• A function can send data back using the return


statement.
• Specifies the particular value to be returned by the
call of the function.
• Causes a dynamic exit from the function.

• Need a variable to catch the data returned.


• Use the value returned in a statement.
• Ignore what has been returned.

15 Programming
Reminder of return types

• Can only return one item of data.


• Can return any of the simple data types.
• We’ll look at how to use return with more complex data
later on.

int foo( int i )


{
i = i * 7;
return i;
}

16 Programming
Two types of parameters

• Two types of parameters


• call by copy
• call by reference

17 Programming
Call by copy

• When a function is called, the value of the parameters


are calculated and passed to the function for
execution.

• Within the function, the parameters act like local


variables.

• The value of the variables used in the parameter list


are unchanged.

18 Programming
Call by copy

• Termed "call by copy" because a copy of the


variable is made.

• Written exactly as the parameter list and


function invocation have been done up until
now.

19 Programming
void CallByCopy( int number )
{
number = 30; // number is changed,
} // but this is local

int main()
{
int a = 10;// 10 assigned to ‘a’
CallByCopy( a );
cout << a;// a still remains 10
}

20 Programming
Reference parameter

• Call by reference using the reference parameter


method is done simply by placing the ampersand
symbol in front of the name of the variable, but after
the data type has been specified.

void FunctionName( int& value )

• Subsequent use of the variable is per normal.

• You can mix call by copy and call by reference.

21 Programming
void ReferanceParameter( int& number )
{
number = 30; // original is changed,
}

int main()
{
int a = 10;// 10 assigned to ‘a’
ReferanceParameter( a );
cout << a;// a now 30
}

22 Programming
Call by reference

• Call by reference is faster than call by copy.

• The return statement only allows one data type to be


sent back from a function.

• Call by reference allows several data types to be sent


back from a function.

• (Return allows the use of dynamic exit, use of a function


within a condition, etc. and this can be useful and lead to
more elegant code.)

23 Programming
Function prototypes

• The compiler needs to know about a function


before it can use it. What if a function is
written after it is called?

• The compiler must be provided with a function


prototype for you to use a function before it
has been defined.

24 Programming
Function prototypes

• Two separate bits of code:


• The function prototype
• The function definition

• The prototype must occur before the function


is used.
• The definition can then be provided anywhere
in the code.

25 Programming
void ReferanceParameter(int& number);

int main()
{
int a = 10;// 10 assigned to ‘a’
ReferanceParameter( a );
cout << a;// a now 30
}

void ReferanceParameter( int& number )


{
number = 30; // original is changed,
}
26 Programming
Second Topic

Files

27 Programming
File I/O

• Very similar to console I/O except that you must declare a


new stream yourself

• There are three types of stream available:


• ifstream - Stream for input (like cin)
• ofstream - Stream for output (like cout)
• fstream - Stream for input/output

• Must include the fstream header:


#include <fstream>

28 Programming
File input

• Looks very similar to standard input.


• Instead of using cin, you declare your own file input stream and
then use this stream.. Substitutee the name of the file stream
for cin.
• Do the following sequence of actions:
• Open a file for input:
ifstream infile("filename");

• Read from an input file:


infile >> data1 >> data2;

• Close an input file once finished:


infile.close();
29 Programming
File Input

• You need to open the file and declare the file


stream.

• You need to check that the file has been opened


successfully, e.g. that the file exists. An error will
occur if you read from a non-existent file.

• You need to close the file after it has been used.

30 Programming
Files and standard input

• A big difference between standard input and


file input is that you must ensure that the file
exists.

• File output will create a new file.

• File input needs the file to already exist.

31 Programming
File input stream

• Open a file for input.

ifstream infile("filename.txt");
if(!infile)
{
cout << "ERROR: ";
cout << "Can't open input file\n";
}

32 Programming
File input

• Imagine writting a program to do a file copy. Read all


of the text from file and output each line of text to a
second file. Do this line by line.

• Would you use a loop?

• What problem now arises?

33 Programming
End of File (EOF)

• With input files, you will need to detect when the end
of the file has been reached:

infile.eof();

• This function returns true if the end of the file has


been reached and false otherwise.
• There is a problem with this which I want to show
with the next code extract.

34 Programming
while( !infile.eof() )
• Why the extra test for
{
end-of-file?
char ch;
infile >> ch; • eof() doesn’t return
if( !infile.eof() ) true until it read after
{ the end of the file. You
cout << ch; will get a spurious extra
} character at the end
} without the test.
• This is one of several
ways to deal with the
issue.
35 Programming
File with function

• Note use of reference parameter

void OpenFile( ifstream& infile )


{
infile.open( "input.txt" );
if( !infile )
{
cout << "ERROR: ";
cout << "Can't open input file\n";
}
}

36 Programming
File with function

void ReadFile( ifstream &infile )


{
// This is a formatting command. It says do not
skip // white space when reading from the input stream
infile >> noskipws;
while( !infile.eof() )
{
char ch;
infile >> ch;
if( !infile.eof() )
{
cout << ch;
}
}
}

37 Programming
File with function

int main( )
{
ifstream infile;

OpenFile( infile );
ReadFile( infile);
}

38 Programming
Third Topic

Writing to a file

39 Programming
Output to a file

• Use "ofstream".
ofstream outfile( "filename" );

• This code opens the file for output.

• The name of the file is "filename".

• The name of the file stream is outfile.

• Remember to check that the file stream exists.

40 Programming
Output to a file

• To write to an output file:

outfile << data1 << data2 << endl;

• Can use all of the i/o commands with files.

41 Programming
File Output

• You need to open the file and declare the file stream.

• You need to check that the file has been opened


successfully, e.g. that the file exists. If the file does not
exist then this action creates the file.

• You need to close the file after it has been used.


outfile.close( );

42 Programming
Check successful opening

• You should always check that the file has been opened
successfully. The file handle equates to a boolean:

• true indicates successfully opened


• false indicates that some error has occurred

43 Programming
#include <iostream>
#include <fstream>
using namespace std;

int main( )
{
ofstream outfile( "output.txt" );
if (!outfile )
{
cout << "Cannot open output file" << endl;
exit(1);
}
outfile << "Written to the file" << endl;
outfile.close( );
}
44 Programming

You might also like