dcs 5085 c++ fundamentals chapter 4. overview basics of a typical c++ environment c++ stream...

42
DCS 5085 DCS 5085 C++ Fundamentals C++ Fundamentals Chapter 4 Chapter 4

Upload: willis-blankenship

Post on 29-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

DCS 5085DCS 5085

C++ FundamentalsC++ Fundamentals

Chapter 4Chapter 4

Page 2: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

OverviewOverview• Basics of a typical C++ Environment• C++ Stream Input/Output• Classic Stream vs. Standard Stream• Iostream Library Header Files• Function• Function Prototypes• Inline Functions• Pointers• References

Page 3: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Simple ProgramSimple ProgramPrinting a Line of TextPrinting a Line of Text

//A first program in C++#include <iostream.h>

int main ( ){ cout << “welcome to C++!\n”; return 0;}

Output: Welcome to C++!

Comment

Function main begins program execution

Header file

Indicated the program ended successfully

Page 4: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.1 C++ Stream Input/Output4.1 C++ Stream Input/Output• C++ I/O occur in streams, which are sequences of bytes.

• The bytes could represent characters, raw data, graphics images, digital speech, digital video, and other..

• C++ provide both “low-level” and “high-level” I/O capacities.

• Low-level I/O– Capabilities specify that some number of bytes should be

transferred.

– Provide high speed, high volume transfer, but not convenient for programmer.

• High-level I/O– Bytes are grouped into meaningful units, such as int, float, char

– These type-oriented capabilities are satisfactory for most I/O other than high-volume file processing.

Page 5: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.2 Classic Stream vs. Standard 4.2 Classic Stream vs. Standard StreamStream

• Classical Stream Libraries– Perform I/O operations in ASCII Characters.– Occupies one byte.– Enable input/output of chars.

• Standard Stream Libraries– Perform I/O operations in Unicode Characters.– Occupies more byte.– Enable to presents most of the world’s commercially

viable language, mathematic symbols and much more.– Additional character type called wchar_t to store

Unicode characters.

Page 6: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.3 Iostream Library Header Files4.3 Iostream Library Header Files

• The C++ iostream library provides basic services that required for all stream-I/O operations.

• The <iostream.h> header file defines the– cin - standard input stream– cout - standard output stream – cerr - unbuffered standard error stream– clog - buffered standard error stream

Page 7: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Stream OutputStream Output• Provided by ostream.• Capabilities for output include

– Output of standard data types with the stream insertion operator (<<).

– Output of characters via the “put” member function.– Unformatted output via the write member function.– Output of integers in decimal, octal and hexadecimal

formats.– Output of floating point values with various precision.– Output of data justified in fields of designated widths,

with forced decimal points, in scientific and fixed notation.

– Output of uppercase letters in scientific notation and hexadecimal notation.

Page 8: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Stream InputStream Input• Provided by istream.

• Input of standard data types with the stream extraction operator (>>).

• stream extraction operator

– Skips whitespace characters (I.e. blank, space, new lines).

– Return 0 (false) when end-of-file is encountered on a stream.

– Otherwise, return a reference to the object that received the extraction message.

Page 9: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.4 Functions4.4 Functions

• Modules in C++ are called functions or classes.• Programmer can simple write a new function or using

pre-packaged functions available in C++ standard libraries.

• The C++ library provides a rich collection of functions for performing common mathematical calculations, string and character manipulations, input/output, error checking and many other useful operations.

• A function invoked by a function call.• The function call specifies the function name and

provides information that the call function needs to do its job.

Page 10: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

• Functions allow the programmer to modularize a program.

• All variable defined in definition are local variables – they are known only in the function in which they are defined.

• Most functions have a parameters that provide the means of communicating information between functions.

• Function’s parameters are also local variables of that function.

• The format of a function definition is as below:

Return-value-type function-name (parameter-list)

{

declarations and statements

}

Page 11: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

//A program in C++#include <iostream.h>

int square(int);

int main ( ){ for(int x=1; x<=10; x++) cout << square(x) << “ “ << endl;

return 0;}

int square(int y){ return y*y;}

Square function

Indicates successful termination

Function prototype

Function call

Output: 1 4 9 16 25 36 49 64 81 100

Page 12: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.5 Function Prototypes4.5 Function Prototypes• A function prototype tells the compiler the

– the name of a function,– the type of the data returned, – the number of parameters, – the type of those parameters,– the order in which the parameter of those types are

expected.• The compiler use function prototype to validate function

calls. • Early versions of C programming language did not

perform this kind of checking, so it was possible to call C functions with incorrect arguments and compiler would not detect the error.

Page 13: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

• Another important feature of function prototypes is the argument coercion.

• I.e. forcing arguments to the appropriate types specified by the parameter declarations.

• Call sqrt( ) with an integer argument even though the function prototype in <cmath> specifies a double argument and the function still work correctly.

• If a conversion do not converts correspond precisely to the types in the function prototype can lead to incorrect results.

• Converting values to lower types can result in incorrect value.

cout << sqrt(4);

double -> int 2.33444 -> 2

Page 14: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.5 Inline Functions4.5 Inline Functions

• Implementing a program as a set of functions is good from a software engineering standpoint, but function calls involve execution time overhead.

• C++ provides inline functions to help reduce function-call overhead – especially for small functions.

• Inline function will “advises” the compiler to generate a copy of the function’s code in place to avoid a function call.

• The compiler can ignore the inline qualifier and typically does so for all but the smallest functions.

• Disadvantages:– Multiple copies of the function code are inserted in the program

rather than having a single copy of the function to which control is passed each time the function is called.

Page 15: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

//A program in C++#include <iostream.h>

inline double cube(const double side){ return side*side*side;}

int main ( ){ double sideValue; cout << “Please enter the side length of the cube: ”; cin >> sideValue;

cout << “Volume of a cube with side ” << sideValue << “ is ” << cube(sideValue) << endl;

return 0;}

Inline function

Compiler make a copy to

Page 16: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

4.6 Pointers4.6 Pointers• Pointer variable contains primary memory address.

• Syntax:

• I.e. Point_type *Pointer_name

100000 0056 1234

000 0056 3333000 0056

1234

.

.

.

.

.

.

Memory addresses Variable

k

*ptr

Type

int

int Integer

Pointer

Absolute addressRelative address

Page 17: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

ReferencesReferences• A reference can be declared either as an ordinary variable

or as a function parameter.• Syntax:

• I.e.

• The character & indicates that we are dealing with a reference.

• A reference can be understood as a constant pointer variable because it always refers to the same variable and cannot itself be changed.

Data_type &data_name

int n;int &ri = n;

Page 18: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

5 10i j885641200 9856210

i = 5&i = 885641200

j = 10&j = 9856210

if k = &ithen k = 885641200, and k* = 5

if m = &jthen m = 9856210, and m* = 10

Page 19: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

void change1(int &, int &);

int main(){ int i = 5, j = 10; change1(i,j); cout << "i " << i << " j " << j <<endl; return 0;}

void change1(int &a, int &b){ int c = a; a = b; b = c;}

Output: i 10 j 5

c = add a thus, c points to 5

add a = address of b, value 10

add b = add of c = 5

Page 20: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

void change2(int *, int *);

int main(){ int i = 5, j = 10; change2(&i,&j); cout << "i " << i << " j " << j <<endl; cout << "i " << &i <<endl; return 0;}

void change2(int *pa, int *pb){ int c = *pa; *pa = *pb; *pb = c;}

Output: i 10 j 5

i 3434366734

c = value at a, thus c holds 5

value at a = value at b, thus a = 10

value at b = c, thus b holds 5;

Page 21: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class

•arrays•string object

Page 22: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

– Data structure

– Grouping of like-type data

– Indicated with brackets containing positive integer constant or expression following identifier

• Subscript or index

– Loops commonly used for manipulation

Code Class >> arrays

Page 23: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

One Dimensional array

– Declaration indicates name and reserves space for all elements

– Values assigned to array elements using assignment statements

– Array names classified as identifiers

– Programmer sets size of array explicitly

Code Class >> arrays

int count[4];

int int int int

Page 24: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

Array Length

– Must be integer constant greater than 0

– Only integer type variables (with modifiers)

• int, char

• signed, unsigned, short, long

– Always within brackets following identifier

– Examples: int count[32]; int count[-25], b[43.5];(invalid)

Page 25: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

Array Subscripts

– First index or subscript is 0

– int arms[2];

• Data type of elements is int

• Name of array is a

• Number of elements is 2

• Valid subscripts are 0 and 1

– Address as arms[0] and arms[1]

arms[0]arms arms[1]

Page 26: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

Initialization

– In declarations enclosed in curly braces

int a[5] = {11,22};

Declares array a and initializes first two elements and all remaining set to zero

int b[ ] = {1,2,8,9,5};Declares array b and initializes all

elementsand sets the length of the array to 5

Page 27: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

using arrays

– Declare int test[3];

• sets aside 3 storage locations

– use index to reference the variables test[0] = 86; test[1] = 92; test[2] = 90;

86 92 90

Page 28: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

example :1) declare and fill array using a for loop

int count[3];for(int i=0 ; i<3 ; i++)count[i]=i;

2) declare and fill array using user inputdouble temperature[4];int count=0;while(count<4) {

cout << “insert temperature “ << count;cin >> temperature[count];count ++; }

Page 29: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

3) print out all values in array scores[]for (int j = 0; j < 20; ++j) { cout << scores[ j ] << endl; }

4) find smallest value in array scores[]small = scores [0];for (int j = 1; j < 20; ++j) { if (scores[ j ] < small) small = scores [ j ]; }

Page 30: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

Array of Objects

– Declared using class name, object name, and brackets enclosing integer constant Vehicle truck[3];

• Three objects (truck[0], truck[1], truck[2] of class Vehicle

– Call member function

• object, dot operator, and function name

truck[0].set_data (50, 2, 3);

Page 31: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

– Good when multiple pieces of information are linked

– Use assignment statement to copy one object array element to another

truck[1] = truck[0];

Page 32: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> arrays

multidimensional arrays or arrays of arrays• create an array that holds other arrays• all arrays must be of same type

double count[3][3]; array count holds3 arrays of type intthat hold 3 valueseach

Page 33: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

– Do not need to specify size of string object

• C++ keeps track of size of text

• C++ expands memory region to store text as needed

– Can use operators to perform some string manipulations

Page 34: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

Declaring

– Use the class name string and list object names

– Example: string s1, s2, s3;

• s1, s2, s3 would be string objects

– String header needed to declare string objects

– Do NOT specify size (Note: no brackets)

Page 35: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

Initializing

– Can initialize with the =

• C++ automatically reserves sufficient memory

– Can also place in ( ) but still need " "

– Null character not required for string text

– Data member of string class stores size of text

e.g. string s1;s1 = “this is an example string”;

Page 36: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

Type Operator ActionAssignment = Stores string

+= Concatenates and storesComparison == True if strings identical

!= True if strings not identical > True if first string greater than second < True if first string is less than second>= True if first string greater or equal than

second<= True if first string less or equal than

secondInput/Output >> For input and string objects

<< For output and string objectsCharacter [ ] To access individual characters accessConcatenation + Connects two strings

Page 37: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

e.g

s1 = “my name is mongo”;s2 = s1;

s3 = “jolly “;s3+=s1;

s4 = s1+s3;

if(s1==s2){ cout << s4; }

s2 -> “my name is mongo”

s3 -> “jolly my name is mongo”

s4 -> “my name is mongo jolly my name is mongo”

Page 38: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

String member functions

– More actions needed than operators can provide

– Calling member function involves using object name with dot operator and function name

• Invoking object

– One that is modified

Page 39: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

find function– Searches for a string within a string– Basic form of call to find

ob1.find (ob2);• finds first occurrence of string ob2 within ob1

– Returns position

s1 = "This is an example.";s2 = "exam";n = s1.find (s2);

012345678901

ans = 11

Page 40: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

Reading Single Word

– From keyboard using cin cin >> s1;

• Reads characters until whitespace typed

• Whitespace includes space and "Enter" key

– Amount of memory for s1 automatically made sufficient

Page 41: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string

Page 42: DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream

Code Class >> string