Rossella Lau Lecture 2, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design ...

41
Rossella Lau Lecture 2, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design Lecture 2: Basic I/O and user-defined functions Good programming practice: Naming and Spacing Basic pre-defined functions of I/O streams Simple I/O formatting in C++ Structured programming User-defined functions Access to variables in different scopes -- By Rossella Lau
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    213
  • download

    0

Transcript of Rossella Lau Lecture 2, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design ...

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

DCO10105 Object-Oriented Programming and Design

Lecture 2: Basic I/O and user-defined functions

Good programming practice: Naming and Spacing Basic pre-defined functions of I/O streams Simple I/O formatting in C++ Structured programming User-defined functions Access to variables in different scopes

-- By Rossella Lau

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Good programming practice – Naming

Apply Java’s naming convention

Experience to follow a world-wide known convention as a starting point

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Class Name

Rules: Noun or noun phase Capitalize the first letter of each word No underscore

Do the following class names follow the rules?class coffeeMaker;

class RecordSales;

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Variable Name

Rules: Word or word phase Lower case for the first letter Capitalize the first letter of subsequent words

Do the following variable names follow the rules? int count_apples; int JulieMoney;

double total_pears;

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Method/Function Name

Rules: Verb or verb phase rules similar to variable names Special/standard names: equals(), toString(), getX(), setX(), isX(), length(), etc

Does the following function name follow the rules? int julieMoney();

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Constant Identifier

All capital letters

Does the following constant name follow the rules? const int SECONDSPERMINUTE = 60;

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Good programming practice – Spacing

Space or white space in a program increases the readability and supports better logic understanding

White space is the blank area in a program It may be a space (input by using the space bar) It may be a tab It may be the “null” area after an Enter is pressed It can result in the program as neat alignment or

indentation and blank lines

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Code alignment

A statement written on several lines with proper space aligning the same column supports pleasant reading; e.g., the cout in cirArea.cpp

Indentation Same level of statements aligned in the same column

supports better readability as well as better debugging• All function declaration aligns on the first column

• Statements of a function starts the second level and the statements align on e.g, the fifth column indentation

• Statements inside a control structure starts a new level

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Blank line

To separate different segments of coding to provide a break for readers to “breathe”

Examples of a segment Statements to do a user prompt Assignments of class data A control structure (selection statement, loop) Statements doing a different task from the later statements

Use consistent number of blank line(s) to separate segments

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Basic of the I/O stream

The sample programs we saw in last lecture using I/O through <iostream>

It includes two streams: istream and ostream

Input can be simply done by cin >> However, user input must be separated by a space or ‘\n’ How to input a full name with a space How to read every character including the space and ‘\n’

Output can be simply done by cout << How to format data such as $200,00.00

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

I/O with predefined functions

To do “advanced” I/O, we need to use some pre-defined functions in the system library

Using pre-defined functions is similar to using Java methods, we need to understand their API specifications

Through the “Useful Links” on the course page, there are some links to read the “API” of the pre-defined functions

Sample Links:http://www.cppreference.com/

http://www.sgi.com/tech/stl/index.html

http://www.cplus.about.com/

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Input with get()

Pattern: istreamInstance.get(varChar)

istreamInstance is an instance of an istream object, e.g., cin

varChar is a variable with data type char

It reads a character from the input istreamInstance without throwing any character in the subsequent input

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Example of get()

Sample program: tryInput.cpp

char letter; cin.get(letter); User input: ‘m’ letter is assigned with value ‘m’

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Input with getLine()

Pattern: getline(istreamInstance, varString, delimiter)

varString is a variable with type of “string”, a class in the STL

delimiter is the “separator” or the end of line indicator Indeed, getLine() is not a function in the istream library, it

is a function defined in <string>

It can read all input on a line until the delimiter specifies and stores the input, except for the delimiter

It used to read a full name which includes a space in between words

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Example of getLine()

Sample program tryInput.cpp

string line; getline(cin, line, ‘\n’);• User input: Chan Tai Man then press Enter•line is assigned with value “Chan Tai Man”

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Redundant input

User input may be redundant in get()

or in cin >> accidentally inputting

a double instead of an integer

Using ignore() can throw away subsequent characters we don’t want

E.g., twoInputs.cpp

// two inputs for cirArea.cpp……//beginning

cerr << “Radius”; cin >> r; area = PI * r * r; cout << "The area: << area << endl;

cerr << “Radius”; cin >> r; area = PI * r * r; cout << "The area: << area << endl;//……ending

cin.ignore(100,’\n’); throw away ,e.g., .3

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Input device reset

When a user inputs a string instead of a numeric data for statements such asint radius;

cin >> radius;

The input stream enters a fail state, that means it cannot work properly any more

To reset the input stream, function clear() can be used to return the input stream to a working device

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

A simple example of resetting input device

Another sample program: Malik: Example 3-6

// two inputs for cirArea.cpp……//beginnings cerr << “Radius”; cin >> r; area = PI * r * r; cout << "The area: << area << endl;

cin.clear(); cin.ignore(100, ‘\n’);

cerr << “Radius”; cin >> r; area = PI * r * r; cout << "The area: << area << endl;……//endings

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Output formatting

Formatting in C++ can use the functions in <iomanip>, the manipulator library with the pattern: ostreamInstance << manipulator;e.g., cout << setprecision(2) << area;

Manipulators can be a function or an identifier

Popularly used manipulators: setprecision(), fixed, showepoint, setw(), setfill() left, right, unsetf() when left or right is used, scope

identifier should be used: e.g.: usetf(ios::left);

Sample program: Malik:3: Movie Ticket Sale

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Forced output

Program outputs are not directly from your program to the output device

They first go to a system buffer, a memory place to store ready output, and wait until the buffer is full, then output

A program can also “force” the output to directly go to the output device by using, e.g., endl, ‘\n’, or a special function flush, e.g., cout << flush;

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Standard I/O redirectStandard input and output files are the keyboard

(cin) and the screen (cout & cerr)

They are ready for use in a program without file opening or closing

These standard I/O files can be re-directed from/to a disk file by running a program as, e.g., :

cirArea < in.dat cirArea > out.txt or cirArea 2> err.txt

Without any explicit file operations inside a program, you can read/write a disk text file from/to a disk file by I/O redirection

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

File streams

You may also explicitly open a file inside your program and once a file is opened, it can be used in the same way as the standard I/O files

File I/O should include the header file <fstream> Similar to iostream, it includes ifstream and ofstream Indeed, ifstream is a sub-class of istream and ofstream is a sub-class of ostream

Instances of ifstream or ofstream can use all functions (and operations) as in e.g., cin and cout respectively

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

File Input and Output

To open a file, you mayFor input file: ifstream inFile(“in.dat”); or ifstream inFile(); inFile.open(“in.dat”);For output file: ofstream outFile(“out.txt”); or ofstream outFile(); outFile.open(“out.txt”);

No matter which way you open a file, remember inFile.close(); outFile.close(); before the program

ends

Sample programs: Malik: 3: Student Grade

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

The structured programming

It may also be called the structured approach to programming

It is also called a top-down design, stepwise refinement, and modular programming:solveProblem ( Problem problem) { if problem = trivial write solution else breakdown problem into N sub-problems define relationship between sub-problems for each sub-problem solveProblem (sub-problem) endfor endif}

Each small solution a function

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

A general model to write program: IPO

Usually, a program requires user to input something then to calculate, or process the input data and finally produce the result and display the results to the screen

This kind of program can apply an Input-Process-Output (IPO) model

E.g., cirArea.cpp can be divided into three parts: Input: the user prompt and accepting user input Process: calculate the area Output: display the area to screen

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

A simple example of structured programming

cirArea.cpp applies the IPO model, i.e., we can divide this kind of program into three parts: input, process, and output

// Headers of cirArea.cpp

perform inputRadius(); perform calculArea(); perform displayResult();

//End of program

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

User-defined function

To implement the “module” we have divided in the first solution, we use “function”

Functions written by a programmer are called user-defined functions

Syntax and components of a C++ function: slide 15 of Lecture 1

With the “function”, we can re-write cirArea.cpp with a list of functions – however, there are relationship among functions – how to make them related?

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Return value and parameters

To make the functions related, some functions should result in a value or carry a value for process, e.g.,

inputRadius() should return the radius int inputRadius();

calculateArea() should return the result of the area and should carry the radius resulted from inputRadius() to calculate the area double calculateArea(int radius);

Similarly void displayArea(int radius, double area);

cirArea.cpp v2.0

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

cirArea.cpp v2.0

cirArea.cpp v1.0 becomes a collection of functions (modules) that’s why the structured programming is also called modular programming

Note that all functions are written before main() in order to pass through the compiler

An int function is not required to be written before main() but for consistency, once you write a function before main(), it is better to write all functions before main()

However, it does not look like top-down

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

cirArea.cpp v2.1

C++ program allows for forward reference and you can declare a function without any implementation in the beginning of a program to allow the implementation of main() to appear as the “first” function in the program list

The declaration of the function without implementation is called function prototype

It requires the return type of a function, the function id, the parameter list; in the parameter list, only the data types of the parameters are required, the parameter ids are optional

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Activating a function

A function with implementation cannot be activated or invoked, unless it is called by an executing statement except for main(), which is the entrance of a program (it is activated when the program starts)

To activate a function means to execute or to invoke a function or to call a function

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Function call with actual parameter values

The statement that activates (calls) a function should pass the required number of parameters (actual parameter value) respectively

In some situation, the passed value may be promoted to another type: e.g., from an integer to a double

The function call results in a value returned by a valued function (return type other than void)

can be used in an expression may need to be stored for further use – it is more efficient

if the result is required in more than one statement – avoid invoking more than once if several function calls are the same

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Execution of a function

A function is activated by a calling action. E.g., the first function call statements in main() of cirArea.cpp

A calling action activates a called function

A called function returns the execution control to the statement after its calling statement or the next action of the calling statement.

int main() {//……radius = inputRadius();area = calculateArea(radius);displayResult(radius, area);……

int inputRadius(void){ int r; cerr << “Input r:”; cin >> r; return r;}

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Parameter passing

The way of parameter passing in cirArea.cpp is called passed by value

In C++, parameter can also be passed by reference without &, a call, e.g., swap(x, y) cannot swap the value of x and y

void swap(int& a, int& b){ int temp = a; a = b; b = temp;}

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Sample coding on exercises

Rewrite Malik: 2.8, 2.11 with structured programming approach

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Variable visibility or accessibility

In C++, variables can be global or local

Global variables are defined outside all function definitions while local variables are defined inside a function definition; e.g., rate, z, and t defined in Malik: 7.6 Scope of an identifier

Local variables can only be accessed (used, visible) inside the function where they are declared

Global variables can be accessed anywhere

If variable names are identical, the local variable will be used unless scope resolution operator is used

if a global name is to be used with an identical local name, you may use e.g., ::z inside main()

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Variable scopes and life of variables

The visibility of local variables is also called the scope of variables

A function is a scope – Local variables and parameters of a function are only visible to the function

A block – a series of statements quoted by braces is also a scope

A class is a scope – class data/objects are visible to the whole class – i.e. visible to all functions inside the class – similar to global variables

Example program in Malik: 7.6 Scope of an identifier

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Automatic variables and static variables

In C++ the default storage type of a variable is automatic unless you declared the variable with the keyword “static”

The life of automatic variables is the same as the execution time of their respective functions

i.e., automatic variables are born when the associated scope is invoked and "die" when the scope is terminated

The static variables, on the other hand, once resident in the memory, will exist during the whole program’s execution

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Side Effect

A function changes the values of a non-local variable

Passed by reference may result in side effects which is undesirable.

Update of global variables may be undesirable

Good program practice: avoid side effects as much as possible

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Summary

Advanced I/O in C++ uses, e.g., get(), getLine(), clear(), ignore() and formatting manipulators in <iomanip>

Structured programming approach can divide a complicated program into manageable small pieces through user-defined functions

In C++, the most general parameter passing is passed by value and passed by reference

Accessing variables should be according to their scope

Naming convention follows Java’s and white space allows for better readability and traceability

Rossella Lau Lecture 2, DCO10105, Semester B,2005-6

Reference

Malik: 1.8.1, 3, 6, 7.1-8

Online C++ references:http://www.cppreference.com/

http://www.sgi.com/tech/stl/index.html

http://www.cplus.about.com/

-- END --