0% found this document useful (0 votes)
12 views

C++ 2 Module

Uploaded by

Leta SK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C++ 2 Module

Uploaded by

Leta SK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Fundamentals of Programming II

WALLAGA UNIVERSITY
COLLEGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE
A Module Prepared for the Course Fundamentals of Programming II

Prepared by:
1. Tolessa Desta (MSC.)

April, 2023
Wallaga, Ethiopia

1|P a ge
Fundamentals of Programming II

Preface
This module is designed for students of Information Science who take the course
“Fundamentals of Programming II”.
The module contains subsequent units followed by unit outlines and unit objectives, so that
readers will have a glance look at each unit’s aim to be focused when going in to the details of
the reading.
Dear Readers, it is appreciable if you would go through each Unit and perform each activity
questions before you proceed to the next unit that would easily help you achieve the general
objective of the module.
Course Introduction
General Objectives of the Course
At the end of the course, students will be able to:
 Define about arrays, pointers, structures and file management in C++ Programming
 Know the syntax of Array Declaration, pointer declaration, structure declaration and file
management concepts in C++ programming languages
 Identify how to access arrays, pointers, structures and files

2|P a ge
Fundamentals of Programming II

CHAPTER ONE
Arrays and Strings
1.1.Array Definition
An array is a collection of identical data objects, which are stored in consecutive memory
locations under a common heading or a variable name. In other words, an array is a group or a
table of values referred to by the same name. The individual values in array are called elements.
Array elements are also variables. Set of values of the same type, which have a single name
followed by an index. In C++, square brackets appear around the index right after the name a
block of memory representing a collection of many simple data variables stored in a separate
array element, and the computer stores all the elements of an array consecutively in memory.
Instead of declaring individual variables, such as number 0, number1, ..., and number 99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99]to represent individual variables. A specific element in an array is accessed by an
index. An array stores a sequence of values, and the values must all be of the same type. A
collection of values all of the same type is said to be homogeneous.
1.2.Properties of arrays
Arrays in C++ are zero-bounded; the index of the first element in the array is 0 and the last
element is N-1, where N is the size of the array. It is illegal to refer to an element outside of the
array bounds, and your program will crash or have unexpected results, depending on the
compiler. Array can only hold values of one type.
Note: All array subscripts begin with zero.
1.3. Array declaration
Declaring the name and type of an array and setting the number of elements in an array is called
dimensioning the array. The array must be declared before one uses in like other variables. In the
array declaration one must define: The type of the array (i.e. integer, floating point, char etc.)
 Name of the array,
The total number of memory locations to be allocated or the maximum value of each subscript.
i.e. the number of elements in the array.
So the general syntax for the declaration is: DataType name array name [array size];

3|P a ge
Fundamentals of Programming II

The expression array size, which is the number of elements, must be a constant such as 10 or a
symbolic constant declared before the array declaration, or a constant expression such
as10*sizeof (int), for which the values are known at the time compilation takes place.
The sizeof Operator
The size of a static array is fixed at compile time. The C++ sizeof operator computes the amount
of memory in bytes that a static array consumes. The code int list[100], set[] = { 1, 2, 3, 4, 5 };
cout << "list: " << (sizeof list) << ", set: " << (sizeof set) << endl; prints list: 400, set: 20 on a
system in which integers use four bytes of storage. This is because list holds 100 integers at four
bytes each, and set holds five integers at four bytes each. The sizeof operator computes the
storage required for any type; for example, cout << "int: " << (sizeof int) << ", double: " <<
(sizeof double) << endl; prints int: 4, double: 8 on systems that store integers in fours bytes and
double-precision floating-point numbers in eight bytes. The number of elements in a statically
allocated array can be obtained from a simple formula: divide the memory occupied by the array
by the number of bytes required for each element.
The following code fragment
int list[100];
double collection[] = { 2.8, 3.33, 0.4, 0.0, 10.4 };
cout << "list: " << (sizeof list)/(sizeof list[0]) << ", collection: " << (sizeof collection)/(sizeof
collection[0]) << endl;
prints list: 100, collection: 5 on all systems regardless of how much memory integers and
floating-point numbers consume. int list[] = { 2, 4, 6, 8 }; // Print the contents of the array
print(list, 4); therefore could be written int list[] = { 2, 4, 6, 8 }; // Print the contents of the array
print(list, (sizeof list)/(sizeof list[0])); to eliminate the literal value 4 as the second parameter.
The programmer then may add extra elements to, or remove elements from, the initialization list
without changing the call to print. The sizeof operator can be used only to compute sizes known
at compile time and is not helpful for dynamically allocated arrays. The code int *list; list = new
int[100]; cout << "list: " << (sizeof list)/(sizeof list[0]) << endl; on most systems prints list: 1
because pointers and integers often require the same amount of memory. Since list’s declared
type is int *, the sizeof operator returns the size of a pointer, not the number of elements in the
dynamicallyallocated array list points to.

4|P a ge
Fundamentals of Programming II

Array size cannot be a variable whose value is set while the program is running. The array square
brackets operator has two distinct meanings depending on the context: 1. At the array’s
declaration, for example, double nums[10]; the number within the square brackets specifies the
number of elements that the array can hold. The compiler uses this number along with the type of
the array to determine how much memory to allocate for the array. 2. After the array’s
declaration, for example, nums[3] = 10.45; the number within the square brackets represents an
index locating a specific element within the memory allocated to the array.
1.4.Initializing Arrays
When declaring an array of local scope (within a function), if we do not specify the array
variable will not be initialized, so its content is undetermined until we store some values in it.
If we declare a global array (outside any function) its content will be initialized with all its
elements filled with zeros. Thus, if in the global scope we declare:
int day [5]; //every element of day will be set initially to 0:

But additionally, when we declare an Array, we have the possibility to assign initial values to
each one of its elements using curly brackets { }.
For example: int day [5] = {16, 2, 77, 40, 12071};
The number of elements in the array that we initialized within curly brackets { } must be equal
or less than the length in elements that we declared for the array enclosed within square brackets
[ ].
If we have less number of items for the initialization, the rest will be filled with zero.
When initializing an array, we can provide fewer values than the array elements. E.g. int a [10] =
{10, 2, 3}; in this case the compiler sets the remaining elements to zero. The contents of an array
may be initialized when it is declared. The following code fragment declares three arrays and
specifies their initial contents:
int list[] = { 2, 4, 6, 8 };
double collection[10] = { 1.0, 3.5, 0.5, 7.2 };
char letters[] = { 'a', 'b', 'c' };
The elements of the array are provided by a comma-separated list within curly braces. This
comma separated list of initial values is called an array initialization list. When an array

5|P a ge
Fundamentals of Programming II

initialization list is provided, the square brackets can be left empty as the compiler can calculate
the array’s size based on the number of elements in the list. If a number is provided within the
square brackets, the array is allocated with the specified size, and the first positions within the
array are filled with the elements specified in the initialization list. The code fragment above
declares three arrays: list, collection, and letters. The list array is created to hold four integer
values consisting of 2, 4, 6, and 8. The collection array is created to hold 10 double-precision
floating-point values, and the first four elements consist of 1.0, 3.5, 0.5, and 7.2. The letters array
holds the three characters shown.
1.5. Prime Generation with an Array
Make a list of all the integers two and larger. Two is a prime number, but any multiple of two
cannot be a prime number (since a multiple of two has two as a factor). Go through the rest of
the list and mark out all multiples of two (4, 6, 8, ...). Move to the next number in the list (in this
case, three). If it is not marked out, it must be prime, so go through the rest of the list and mark
out all multiples of that number (6, 9, 12, ...). Continue this process until you have listed all the
primes you want.
#include <iostream>
#include <ctime>
using namespace std;
// Display the prime numbers between 2 and 500,000 and
// time how long it takes
// Largest potential prime considered
//const int MAX = 500000;
const int MAX = 500;
// Each position in the Boolean array indicates
// if the number of that position is not prime:
// false means "prime," and true means "composite."
// Initially all numbers are prime until proven otherwise
bool nonprimes[MAX]; // Global array initialized to all zeros
int main() {
clock_t start_time = clock(); // Record start time
// First prime number is 2; 0 and 1 are not prime

6|P a ge
Fundamentals of Programming II

nonprimes[0] = nonprimes[1] = true;


// Start at the first prime number, 2.
for (int i = 2; i < MAX; i++) {
// See if i is prime
if (!nonprimes[i]) {
cout << i << " ";
// It is prime, so eliminate all of its
// multiples that cannot be prime
for (int j = 2*i; j < MAX; j += i)
nonprimes[j] = true;
}
}
cout << endl; // Move cursor down to next line
// Print the elapsed time
cout << "Elapsed time: "
<< static_cast<double>(clock() - start_time)/CLOCKS_PER_SEC
<< " seconds" << endl;
}
1.6.Accessing and processing array elements
In any point of the program in which the array is visible we can access individually anyone of its
elements for reading or modifying it as if it was a normal variable.
To access individual elements, index or subscript is used.
The format is the following: name[ index ]
In c++ the first element has an index of 0 and the last element has an index, which is one less the
size of the array (i.e. array size-1).
Thus, from the above declaration, day [0] is the first element and day [4] is the last element.
Following the previous examples where day had 5 elements and each element is of type int, the
name, which we can use to refer to each element, is the following one:

7|P a ge
Fundamentals of Programming II

For example, to store the value 75 in the third element of the array variable day a suitable
sentence would be: day [2] = 75; //as the third element is found at index 2 And, for example, to
pass the value of the third element of the array variable day to the variable a, we could write: a
= day [2];
At this point it is important to be able to clearly distinguish between the two uses the square
brackets [ ] have for arrays.
 One is to set the size of arrays during declaration
 The other is to specify indices for a specific array element when accessing the elements of
the array.
Example: - display the sum of the numbers in the array
#include <iostream>
int main ()
{
int day [ 5] = {16, 2, 77, 40, 12071};
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{ result += day[n];
} std::cout<< result;
return 0;
}
1.7. Multidimensional arrays
In C++ you can define multidimensional arrays with any number of dimensions.
The most common multidimensional array type is the two-dimensional array, the so called
matrix. Multidimensional arrays with two dimensions are often used to represent tables of
values consisting of information arranged in rows and columns.
To identify a particular table element, we must specify two subscripts.
By convention, the first identifies the element's row and the second identifies the element's
column. Arrays that require two subscripts to identify a particular element are called two-
dimensional arrays or 2-D arrays. Note that multidimensional arrays can have more than two
dimensions (i.e., subscripts). The following figure illustrates a two dimensional array. The array
contains three rows and four columns, so it is said to be a 3-by-4 array. In general, an array with

8|P a ge
Fundamentals of Programming II

m rows and n columns is called an m-by-n array. Multidimensional arrays can be described as
"arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table
made of elements, all of them of a same uniform data type.

Every element in array a is identified in the above figure by an element name of the form a[i][ j],
where a is the name of the array, and i and j are the subscripts that uniquely identify each
element in a. Notice that the names of the elements in row 0 all have a first subscript of 0; the
names of the elements in column 3 all have a second subscript of 3.
// multidimensional array
#include <iostream>
int matrix [5][3];
int n,m,i,j;
int main ()
{ for (n=0;n<5;n++)
{ for (m=0;m<3;m++)
{ matrix [n][m]=(n+1)*(m+1);//1*1=1,2*1=2,3*1=3,4*1=4,5*1=5
}//1*2=2,2*2=4,3*2=6,4*2=8,5*2=10
}//1*3=3,2*3=6,3*3=9,4*3=12,5*3=15
for (i=0;i<5;i++)
{ for(j=0;j<3;j++)
{ std::cout<<matrix [i][j]<<"\t";
}
std::cout<<"\n";

9|P a ge
Fundamentals of Programming II

}
return 0; }
1.8.Arrays as parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not
possible to pass a complete block of memory by value as a parameter to a function, but we
are allowed to pass its address. In practice, this has almost the same effect and it is a much
faster and more efficient operation. In order to accept arrays as parameters the only thing that
we have to do when declaring the function is to specify in its parameters the element type of
the array, an identifier and a pair of void brackets []. For example, the following function:
void procedure (int arg[]) accepts a parameter of type "array of int" called arg. In order to
pass to this function an array declared as: int myarray [40];
Exercise:
 Create an array of type string called cars.
 string cars[4] = {“bus", “car", “bajaj", “isuze"};
1.9. Strings of Characters
In all programs and concepts we have seen so far, we have used only numerical variables,
used to express numbers exclusively. But in addition to numerical variables there also exist
strings of characters that allow us to represent successive characters, like words, sentences,
names, texts, etc. Until now we have only used them as constants, but we have never
considered variables able to contain them. In C++ there is no specific elementary variable
type to store string of characters. In order to fulfill this feature we can use arrays of type
char, which are successions of char elements. Remember that this data type (char) is the one
used to store a single character, for that reason arrays of them are generally used to make
strings of single characters. For example, the following array (or string of characters) can
store a string up to 20 characters long. You may imagine it thus: char name [20];

This maximum size of 20 characters is not required to be always fully used. For example, name
could store at some moment in a program either the string of characters "Hello" or the string“
10 | P a g e
Fundamentals of Programming II

studying C++”. Therefore, since the array of characters can store shorter strings than its total
length, there has been reached a convention to end the valid content of a string with a null
character, whose constant can be written as '\0’. We could represent name (an array of 20
elements of type char) storing the strings of characters
"Hello" and "Studying C++" in the following way:

Notice how after the valid content it is included a null character ('\0') in order to indicate the end
of string. The empty cells (elements) represent indeterminate values.
1.10. Initialization of Strings
Because strings of characters are ordinary arrays they fulfill same rules as any array. For
example, if we want to initialize a string of characters with predetermined values we can do it in
a similar way to any other array: char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared a string of characters (array) of 6 elements of type char
initialized with the characters that compose Hello plus a null character '\0’.
Unlike single quotes ( ' ) which allow to specify single character constants, double quotes ( " )
are constants that specify a succession of characters.
These strings enclosed between double quotes have always a null character ( '\0' ) automatically
appended at the end.
Therefore we could initialize the string mystring with values by any of these two ways:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
Notice how after the valid content it is included a null character ('\0') in order to indicate the end
of string.
The empty cells (elements) represent indeterminate values.
In both cases the Array or string of characters mystring is declared with a size of 6
characters(elements of type char ): the 5 characters that compose Hello plus a final null

11 | P a g e
Fundamentals of Programming II

character ( '\0' )which specifies the end of the string and that, in the second case, when using
double quotes ( ")it is automatically appended.
Before going further, you should note that the assignation of multiple constants like double
quoted constants ( " ) to arrays are only valid when initializing the array, that is, at the moment
when declared.
The following expressions within a code are not valid for arrays mystring="Hello";
mystring[] = "Hello"; neither would be: mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
So remember: We can "assign" a multiple constant to an Array only at the moment of initializing
it. The reason will be more comprehensible when you know a bit more about pointers, since then
it will be clarified that an array is simply a constant pointer pointing to an allocated block of
memory.
And because of this constant feature, the array itself cannot be assigned any value, but we can
assign values to each of the elements of the array.
At the moment of initializing an Array it is a special case, since it is not an assignation, although
the same equal sign (=) is used.
Anyway, have always present the rule previously underlined.
1.11. Assigning Values to Strings
Just like any other variables, array of character can store values using assignment operators. But
the following is not allowed. mystring=”Hello”;
This is allowed only during initialization.
Therefore, since the value of an assignation can only be an element of an array and not the entire
array, what would be valid is to assign a string of characters to an array of char using a method
like this:
 mystring[0] = 'H';
 mystring[1] = 'e';
 mystring[2] = 'l';
 mystring[3] = 'l';
 mystring[4] = 'o';
 mystring[5] = '\0';
But as you may think, this does not seem to be a very practical method.

12 | P a g e
Fundamentals of Programming II

Generally for assigning values to an array, and more specifically to a string of characters, a series
of functions like Strcpy are used.
1.12. Functions to manipulate strings
The cstring library ( string.h ) defines many functions to perform some manipulation operations
with C-like strings (like strcpy). Here you have a brief with the most usual:
A. String length
Returns the length of a string, not including the null character (\0).
strlen (const char* string );
B. String Concatenation
Appends src string at the end of dest string. Returns dest.
The string concatenation can have two forms, where the first one is to append the whole content
of the source to the destination the other will append only part of the source to the destination.
Appending the whole content of the source
strcat (char* dest, const char* src);
Appending part of the source
strncat (char* dest, const char* src, int size );
Where size is the number characters to be appended
C. String Copy
Overwrites the content of the dest string by the src string.Returns dest.
The string copy can have two forms, where the first one is to copying the whole content of the
source to the destination and the other will copy only part of the source to the destination.
Copy the whole content of the source
strcpy (char* dest, const char* src);
Appending part of the source
strncpy (char* dest, const char* src, intsize );
Where size is the number characters to be copied
D. String Compare
Compares the two string string1 and string2. The string compare can have two forms, where the
first one is to compare the whole content of the two strings and the other will compare only part
of the two strings.
Compare the whole content of the source

13 | P a g e
Fundamentals of Programming II

strcmp (const char* string1 , const char* string2 );


Compare part of the source
strncmp (const char* string1 , const char* string2, int size );
Where size is the number characters to be compared
Both string compare functions returns three different values:
Returns 0 if the strings are equal
Returns negative value if the first is less than the second string
Returns positive value if the first is greater than the second string
Example: Predict the output of the following code fragment
#include <iostream>
#include<string>
int main()
{
char A[20]="Computer";
char B[20]="programming";
char C[20];
cout<<strcpy(C,A)<<endl;
cout<<strcat(A,B)<<endl;
cout<<strlen(A)<<endl;
cout<<strncpy(C,A,8)<<endl;
strcpy(C,"Computer");
cout<<strncmp(C,A,8);
return 0;
}
Exercises
1. Can you declare an array to hold a mixture of ints and doubles?
2. What happens if you attempt to access an element of an array using a negative index?
3. Given the declaration int list[100]; (a) What expression represents the very first element of
list? (b) What expression represents the very last element of list? (c) Write the code fragment that
prints out the contents of list. (d) Is the expression list[3.0] legal or illegal?

14 | P a g e
Fundamentals of Programming II

4. Is the following code fragment legal or illegal? int list1[5], list2[5] = { 3, 3, 3, 3, 3 }; list1 =
list2;
5. Provide a single declaration statement that declares an integer array named list that contains
the values 45, −3, 16 and 8?
6. Does an array keep track of the number of elements it contains?
7. Complete the following function that adds up all the positive values in an array of integers.
For example, if array arr contains the elements 3, -3, 5, 2, −1, and 2, the call sum_positive(arr)
would evaluate to 12, since 3 + 5 + 2 + 2 = 12. The function returns zero if the array is empty
(that is, n ¡ 1).
// Array a with length n int sum_positive(const int *a, int n) { // Add your code... }
8. Complete the following function that counts the even numbers in an array of integers. For
example, if array arr contains the elements 3, 5, 2, −1, and 2, the call count_evens(arr) would
evaluate to 4, since 2 + 2 = 4. The function returns zero if the array is empty (that is, n ¡ 1). The
function does not affect the contents of the array. // Array a with length n int count_evens(const
int *a, int n) { // Add your code... }
9. Complete the following function that counts the even numbers in a 2D array of integers. // 2D
array v with r rows and c columns int count_evens(const int **v, int r, int c) { // Add your code...
}
10. Suppose your task is to implement the function with the prototype void proc(int a[]); When
you implement the body of proc, how can you determine the size of array a?
11. Consider the declaration int collection[100][200]; What does the expression collection
[15][29] represent?
12. Consider the declaration int collection[100][200]; How many elements does collection hold?
13. Consider the declaration int collection[100][200]; Write the C++ code that prints all the
elements in collection. All the elements in the same row should appear on the same line, and but
each successive row should appear on its own line.
14. Consider the declaration int collection[100][200]; What does the expression collection[15]
represent?
15. Consider the declaration int mesh[100][200][100][50]; How many elements does mesh hold?

15 | P a g e
Fundamentals of Programming II

Chapter Two
Pointers
At the end of the chapter, students will be able to:
 Define the pointer
 Identify address and pointer
 Know the difference between pointer and array
 Know the difference between pointer and function
 Know the difference between pointer and string
Pointer Variables
Every data in the computer’s memory is stored in addressed places called bytes. The amount of
byte a data takes in the computer’s memory depends on its type i.e. whether the data is char, int,
float, double, etc .though it differs from machine to machine, char data type takes 1 byte
memory; int takes 2 bytes, etc. Every byte in the computer’s memory has an address number.
So, when your program is loaded into memory, every variable in your program occupies portions
of these addressed bytes starting at a particular address and extends a certain range of bytes;
based on the data type, it extends 1 address long for char data type, 2 addresses for int, etc note
that this amount changes from machine to machine. A pointer is a construct that gives you more
control of the computer’s memory. A pointer is the memory address of a variable.
A pointer is a variable that holds the address of some other variable.
The computer’s memory is divided into numbered memory locations (called bytes) and that
variables are implemented as a sequence of adjacent memory locations.
To use pointer:
 We define a pointer variable.
 Assign the address of a variable to a pointer.
 Finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand.
Example: int a=10; //normal variable
int*p; //declare pointer
p = &a; // Assign the address of a variable “a” to a pointer “p”
cout<< “a=”<<*p; // prints a=10

16 | P a g e
Fundamentals of Programming II

A pointer can be stored in a variable. However, a pointer is a memory address and a memory
address is a number, you cannot store a pointer in a variable of type int or double without type
casting. A variable to hold a pointer must be declared to have a pointer type. For example, the
following declares p to be a pointer variable that can hold one pointer that points to a variable of
type double: double *p;
The variable p can hold pointers to variables of type double, but it cannot normally contain a
pointer to a variable of some other type, such as int or char.
Each variable type requires a different pointer type.
A pointer is a special variable we defined in the program which is used to hold the memory
address of another variable.
The Data Type of the pointer variable depends on the data type of that variable which addresses
it is supposed to hold.
It is a special variable because when we define a pointer it contains an asterisk (*) symbol before
the variable name.
The asterisk (*) symbol before a variable makes it a pointer and guide it to point that value
which addresses it hold.
Pointer syntax: Data_Type *variable name;
Example

Pointers to void (void pointers)


We cannot assign the address of a float type variable to a pointer to int as follows.
float f; int *P; P = &f; // this is illegal statement
Similarly float *P; int x;
P = &x; // again this is illegal

17 | P a g e
Fundamentals of Programming II

That means, we can assign the address of variable to pointer variable only when variable data
type and pointer data type is the same (identical).
Then if both are different type, then we can’t assign the address of variable to pointer variable.
But, in C++ this is possible by declaring pointer variable as a void as follows: void *P;
The above pointer is called pointer to void type or void pointer.
That means pointer P point any type of data type; int, float, char, etc. void *P;
int x; float y; P = &y; // ok
P = &x; // ok, because P is void pointer.
Accessing the variable pointed to
We say earlier that an asterisk (*) before a variable name in a declaration tells the compiler that
this is a pointer. Example: int *pi; int j;
pi = &j; pointer pi is assigned the address of the variable j( not the content of j)
But, an asterisk before a pointer variable in the code (i.e. after the pointer is declared) indicates
that we are referring to the variable, (the contents of the variable) which the pointer is pointing.
Example *pi = 4; means we are assigning 4 to the memory location which is addressed by the
pointer pi.
Example
#include<iostream>
using namespace std;
void main ( )
{
int num1 = 10, num2 = 20;
int *p;
p = &num1;
cout<<p<<endl; // displays address of num1
cout<<*p<<endl; // displays content of the address (i.e. 10)
*p = 15; // changing the contents of the address p
cout<<num1<<endl; // displays 15 (not 10)
p = &num2; // pointer points to num2
cout<<*p<<endl; // displays content of the address (i.e. 20)
*p = 120; // assigning 120 to the contents of the address in p

18 | P a g e
Fundamentals of Programming II

cout<<num2<<endl; // displays 120 (not 20)


}
Using the asterisk (*) to access the value stored in an address is called indirect addressing or
sometimes dereferencing the pointer.
E.g. int v;
int *p;
p = &v;
v = 3; // assigns 3 to v
*p = 3; // also assigns 3 to v, since p has the address of v
*&v = 3; // this too assigns 3 to v
Pointer Variable Declarations
A variable that can hold pointers to other variables of type Type_Name is declared similarly to
the way you declare a variable of type Type_Name, except that you place an asterisk at the
beginning of the variable name. Syntax Type_Name *Variable_Name1, *Variable_Name2, . . .;
Example double *pointer1, *pointer2;
Examples of pointers:
int *int_pointer; // pointer to integer
float * float_pointer; // pointer to float
char *str; // pointer to a char or string
int *ptr_ptr; // pointer to a pointer
Addresses and Numbers
A pointer is an address, and an address is an integer, but a pointer is not an integer. That is not
crazy. That is abstraction! C++ insists that you use a pointer as an address and that you not use it
as a number. A pointer is not a value of type int or of any other numeric type. You normally
cannot store a pointer in a variable of type int. If you try, most C++ compilers will give you an
error message or a warning message. Also, you cannot perform the normal arithmetic operations
on pointers. (You can perform a kind of addition and a kind of subtraction on pointers, but they
are not the usual integer addition and subtraction.)
Pointer Operators
There are two special operators that are used with pointers:
Address Operator (&) : “address of …” operator

19 | P a g e
Fundamentals of Programming II

Returns memory address of its operand


A unary operator which returns the memory address of its operand.
& is the reference operator and can be read as "address of“
Example int y = 5; int *yPtr;
yPtr = &y; assigns the address of variable y to pointer variable yPtr
Variable yPtr “points to” y
yPtr indirectly references variable y’s value

Figure; - Graphical representation of a pointer pointing to a variable in memory.


* :“value at address …” operator
A unary operator which returns the value of the variable located at the address specified by its
operand.
is the dereference operator and can be read as "value pointed by“
A variable referenced with & can be dereferenced with *.
Also called indirection operator or dereferencing operator
Returns synonym for the object its operand points to
*yPtr returns y (because yPtr points to y)
Dereferenced pointer is a value
*yptr = 9;
* and & are inverses of each other
Will “cancel one another out” when applied consecutively in either order
Working with Pointers
1. Assigning Values through Pointers
Pointers can be used on the left side of assignment statements.
The following code fragment assigns a value to the location pointed to by the pointer.
int *ptr;
*ptr = 101;
“At the location pointed to by p, assign the value 101.”

20 | P a g e
Fundamentals of Programming II

Increment and decrement operations work on pointers, too. (*ptr)++;


“At the location pointed to by p, increment the value by 1.”
2. Pointer Expressions
Pointer can be used in most C++ expressions.
Use parentheses around pointer expressions
3. Pointer arithmetic
Only four arithmetic operators can be used on pointers. ++,--, +,-
4. Pointer Comparisons
Pointers may be compared using relational operators such as !=,==,< and >
Pointer and array
An array is a pointer. An array is considered to be the same thing as a pointer to the first item in
the array. An array of integers has type int*.
An array is a pointer, and you can store that pointer into any pointer variable of the correct type.
For example, int A[10];
int* p = A; p[0] = 0; makes variable p point to the first member of array A. Setting p[0] = 0
is equivalent to setting A[0] = 0, since pointers p and A are the same.
An array is represented by a variable that is associated with the address of its first storage
location. A pointer is also the address of a storage location with a defined type, so D permits the
use of the array [ ] index notation with both pointer variables and array variables.
For example, the following two D fragments are equivalent in meaning:
p = &a[0]; trace(a[2]); trace(p[2]);
With a regular array declaration, you get a pointer for free.
The name of the array acts as a pointer to the first element of the array.
int list[10]; // the variable list is a pointer
// to the first integer in the array
int * p; // p is a pointer. It has the same type as list.
p = list; // legal assignment. Both pointers to int.
In the above code, the address stored in list has been assigned to p. Now both pointers point to
the first element of the array. Now, we could actually use p as the name of the array! list [3] =
10; p[4] = 5; cout << list[6]; cout << p[6];
Pointer and string

21 | P a g e
Fundamentals of Programming II

String
A String is a collection of characters in a sequential manner. Using a pointer, we can also access
the string elements stored in the form of Array. As we know that the pointer should be of same
data type, which addresses it supposed to hold so the pointer would be of char type. A pointer
can only hold one address at a time so at first, we hold the address of the first character of string
then using the arithmetic + operator then we increment the pointer address with the size of each
character so the pointer can hold the address of next element and point to its value.
The variable string itself represents the address of the string [0] element and using the + operator
we increment the address location by one character to get the address of next character.

String Pointer Array

A pointer variable is used to store the address of another The array is used to store the elements of
variable the same data types.

A pointer can hold the address on one element at a time An array can hold many elements at a time

Data type *variable_name; Data Type variable_name[size];

If we use a pointer to access the elements of a string it Array indexing speed is less than Pointer
would show better performance as compare to Array accessing speed.
indexing

The data type of a pointer variable depends on the data type An array can hold only similar data types
of address variable elements at a time.

Pointer store the address of the variable An array stores the value of variables

22 | P a g e
Fundamentals of Programming II

Chapter Three: - Structures


At the end of the chapter, students will be able to:
 Define a structure variable
 Declare structures
 Initialize structure
 Access structure variable
 Define Function and structure
 Know array of structures
 Identify array with in structures
 Illustrate Structure with in a structure( nested structure)
Structure
In C++, a structure is a collection of variables that are referenced under one name. This
provides a convenient means of keeping related information together. Structures are referred to
as compound data types; they consist of several different variables, which are yet logically
connected. Also known as tuples or records in other languages.
Used to represent a record .
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member, for your program.
The format of the struct statement is this (structure declaration):
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
C++ Structure is a collection of different data types under the same name. A structure is a
collection of items of different data types. It is very useful in creating complex data structures
with different data type records. A structure is defined with the struct keyword. A structure is a
user-defined data type in C++. A structure creates a data type that can be used to group items of
possibly different types into a single line.

23 | P a g e
Fundamentals of Programming II

Structure are different form array because arrays only hold data of similar data types, on the
other hand structure can store data of multiple data types.
It is similar to a class in that, both holds a collection of data of different data types. Each element
in the structure is called a member.
Structures in C++ are user-defined data types that are used to store a group of items of non-
similar data types.
struct Student
{ char name[10];
int roll_number, total_marks;
float average;
}stn;
 The general form of a structure declaration is:
 Struct struct_type_name{
 type member_name_1;
 type member_name_2;
...
 type member_name_N;
 }structure_variables;
The variables that comprise the structure are called members, elements, or fields.
Structure in C++ can contain two types of members:
 Data Member: These members are normal C++ variables. we can create a structure with
variables of different data types in C++.
 Member Functions: These members are normal C++ functions.
Along with variables, we can also include functions inside a structure declaration.
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition.
At the end of the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional.
Here is the way you would declare the Library structure:
struct Library {
char title[50];

24 | P a g e
Fundamentals of Programming II

char author[50];
char subject[100];
int book_id;
} book;
Example 1
// Data Members
char name[50];
int age;
int marks; // Member Functions void student Details(){
cout << "Name: " << name<< endl;
cout <<"Age: " << age << endl;
cout << "Marks: " << marks; }
In the above structure, the data members are two integer variables and one character variable to
store age, marks and name of any student and member function is student Details() which is
printing all of the above details of any student.
Example 2: C++ Program to assign data to a structure variable and display it
// C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct Person{ char name[30];
int age; int citizenship; };
int main(){ Person p1;
cout << "Enter Full name: "; cin.get(p1.name, 30);
cout << "Enter age: "; cin >> p1.age;
cout << "Enter citizenship: "; cin >> p1.citizenship;
cout << "\nDisplay Person Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "citizenship: " << p1.citizenship; return 0; }
Example 3
#include <iostream>

25 | P a g e
Fundamentals of Programming II

#include <string>
using namespace std;// Declare a structure named "car"
struct car {string brand; string model; int year;};
int main() { // Create a car structure and store it in myCar1;
car myCar1; myCar1.brand = "BMW"; myCar1.model = "X5";
myCar1.year = 1999; // Create another car structure and store it in myCar2;
car myCar2; myCar2.brand = "Ford"; myCar2.model = "Mustang";
myCar2.year = 1969;// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
Example 4
#include <cstring> using namespace std;
struct student { int roll_no; string name; int phone_number; };
int main(){ struct student stud[5]; int i; for(i=0; i<5; i++){ //taking values from user cout <<
"Student " << i + 1 << endl;
cout << "Enter roll no" << endl; cin >> stud[i].roll_no;
cout << "Enter name" << endl; cin >> stud[i].name;
cout << "Enter phone number" << endl; cin >> stud[i].phone_number; }
for(i=0; i<5; i++){ //printing values
cout << "Student " << i + 1 << endl;
cout << "Roll no : " << stud[i].roll_no << endl;
cout << "Name : " << stud[i].name << endl;
cout << "Phone no : " << stud[i].phone_number << endl; } return 0; }
Accessing Structure Members
To access any member of a structure, we use the member access operator (.)
The member access operator is coded as a period between the structure variable name and the
structure member that we wish to access.
You would use struct keyword to define variables of structure type.
The instance of the structure is known as "Structure variable".

26 | P a g e
Fundamentals of Programming II

The variable of the structure can be accessed by simply using the instance of the structure
followed by the dot (.) operator and then the field of the structure. For example: s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using the dot
(.) operator and assign the value 4 to the id field.
Example
#include <iostream>
using namespace std;
struct Sphere
{
int radius;
};
int main ()
{
struct Sphere circle;
circle.radius=8;
cout<<"Area of Sphere is: "<<(4*3.14* circle.radius*circle.radius)<<endl;
return 0;
}
Basic differences between structures and array

No Key Structures Array

1 Definition Structure can be defined as a In other hand Array is a type of data structure
data structure used as used as container which can hold variables of
container which can hold same type and do not support multiple data type
variables of different types. variables.

2 Memory Memory allocation for input While in case of array the input data stored in
Allocation data in structure does not contiguous memory allocation which implies
necessary to be in that array stores data in such memory model
consecutive memory where it assigns consecutive memory blocks
location. (that is, memory blocks having consecutive

27 | P a g e
Fundamentals of Programming II

addresses).

3 Accessibility In order to access the On other hand in case of Array we can access the
element in Structure we element by index.
require to have the name of
that element i.e it is
mandatory to have element
name for its retrieval from
Structure.

4 Pointer Structure do not have On other hand in case of Array it internally


concept of Pointer internally. implements Pointer which always points to the first
element of Array.

5 Instantiation Structure object can be On other hand in case of Array we can't create its
created after declaration object after declaration.
later in the program.

6 Data Type Structure supports multiple On other hand in case of Array we can't have
data-type variables as input. different data-type variable as input as it only
supports same type data variables.

Example: C++ Structure


C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct Person
{ char name[50];
int age;
float salary; };
int main() {
Person p1; cout << "Enter Full name: "; cin.get(p1.name, 50); cout << "Enter age: "; cin >> p1.

28 | P a g e
Fundamentals of Programming II

age; cout << "Enter salary: "; cin >> p1.salary; cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl; cout <<"Age: " << p1.age << endl; cout << "Salary: " <<
p1.salary; return 0; }
Here a structure Person is declared which has three members name, age and salary.
Arrays of Structures
It is common to use arrays of structures. However, the structure has to be defined first, before
any array declarations that refer to this particular structure. We can also make an array of
structures. Example:
struct employee {
char name[80];
float hours;
float wage;
};
employee staff[100];
Any entry in the database can be referred to by using the dot operator:
cout << staff[81].name;
staff[3].hours = 38.5;
#include <iostream> #include <cstring>
using namespace std;
struct student { int roll_no; string name;
int phone_number; }; int main()
{ struct student stud[5]; int i; for(i=0; i<5; i++){ //taking values from user
cout << "Student " << i + 1 << endl;
cout << "Enter roll no" << endl;
cin >> stud[i].roll_no; cout << "Enter name" << endl;
cin >> stud[i].name; cout << "Enter phone number" << endl;
cin >> stud[i].phone_number; } for(i=0; i<5; i++){ //printing values
cout << "Student " << i + 1 << endl; cout << "Roll no : " << stud[i].roll_no << endl;
cout << "Name : " << stud[i].name << endl;
cout << "Phone no : " << stud[i].phone_number << endl;
} return 0; }

29 | P a g e
Fundamentals of Programming II

#include <iostream>
using namespace std;
struct my_struct {
int x = 10; };
int main()
{ my_struct my_ob;
cout << my_ob.x;
}
Structure and Functions
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge; };
void printStudentInfo(Student);
int main()
{ Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"Enter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
printStudentInfo(s);
return 0; }
void printStudentInfo(Student s)
{ cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge; }

30 | P a g e
Fundamentals of Programming II

Passing by Reference (address):


It is certainly possible to pass structures by value, which passes a copy of the original structure
to a function.
The disadvantage to this process is evident when dealing with large structures which will
increase memory requirements and slow the system down.
Consequently, passing by reference is the most economical method of dealing with structures
and functions.
The function will access the actual address locations of where the structures are stored as
opposed to working with copies of the structures.
//Sample Program using STRUCTURES and FUNCTIONS ...
//shows global nature of structure, passed by REFERENCE, use of ARRAY.
# include <iostream.h>
# include "apstring.cpp"
# include <apvector.h>
struct STUDENT_TYPE
{ apstring name, course;
double average, finalExam;
};//function prototypes
STUDENT_TYPE get_student( );
void print_student(STUDENT_TYPE & pupil);
int main(void) { //declare the array of students
apvector <STUDENT_TYPE> list(10); // input the list of students
for(int i = 0; i < 10; i++)
{ cout<<"Please enter information for student " << i+1 << endl << endl;
list[ i ] = get_student( ); //use function to get individual info
} // print the array of students one struct at a time
for(int j = 0; j < 10; j++)
{ print_student(list [ j ] );
} return 0;}
//function to read in structure information (returns a structure)
STUDENT_TYPE get_student( )

31 | P a g e
Fundamentals of Programming II

{ STUDENT_TYPE pupil;
apstring dummy;
cout << "Enter the name (last name, first name): ";
getline( cin, pupil.name);
cout << "Enter the course name: ";
getline( cin, pupil.course);
cout << "Enter the course average: ";
cin>>pupil.average;
cout << "Enter the final exam grade: ";
cin>> pupil.finalExam;
getline(cin,dummy);
cout<<endl <<endl;
return pupil;}
//function to print structure
void print_student(STUDENT_TYPE &pupil)
{
cout << "Name: " <<pupil.name<< endl;
cout << "Course: " <<pupil.course <<endl;
cout << "Average: " << pupil.average << endl;
cout << "Final Exam: " << pupil.finalExam << endl <<endl;
return;
}
Pointers to Structures
Like we have pointers to int, char and other data-types, we also have pointers pointing to
structures. These pointers are called structure pointers.
Now, how to define a pointer to a structure? The answer is below:
struct structure_name
{
data-type member-1;
data-type member-1;
data-type member-1;

32 | P a g e
Fundamentals of Programming II

data-type member-1;
};
int main()
{
struct structure_name *ptr;
}
#include <iostream>
#include <cstring>
using namespace std;
struct student
{ string name;
int roll_no; }; int main()
{ struct student stud = {"Sam",1};
struct student *ptr; ptr = &stud
cout << stud.name << stud.roll_no << endl;
cout << ptr->name << ptr->roll_no << endl;
return 0; }
struct student *ptr; - We declared 'ptr' as a pointer to the structure student.
ptr = &stud - We made our pointer ptr to point to the structure variable stud. Thus, 'ptr' now
stores the address of the structure variable 'stud'.
This is the same which we do while defining a pointer to any other variable.
cout << ptr->name << ptr->roll_no << endl; - We use -> operator to access the members of a
structure using a pointer to that structure.
Structure to Function
We can also pass a structure to a function.
There are two methods by which we can pass structures to functions.
Passing by Value
Passing by Reference
Passing by Value
In this, we pass structure variable as an argument to a function. Let's see an example to make it
clearer.

33 | P a g e
Fundamentals of Programming II

#include <iostream>#include <cstring> using namespace std; struct student {


int roll_no; string name; int phone_number; };
void display(struct student st) {
cout << "Roll no : " << st.roll_no << endl;cout << "Name : " << st.name << endl;
cout << "Phone no : " << st.phone_number << endl;} int main(){ struct student s;
s.roll_no = 4; s.name = "Ron"; s.phone_number = 888888; display(s); return 0; }
How to create the instance of Structure?
Structure variable can be defined as:
Student s;
Here, s is a structure variable of type Student.
When the structure variable is created, the memory will be allocated.
Student structure contains one char variable and two integer variable.
Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8.
The total memory occupied by the s variable is 9 byte.
Nesting structures
struct movies_t { string title;
int year;
};
struct friends_t { string name;
string email;
movies_t favorite_movie;
} charlie, maria;
friends_t * pfriends = &charlie;

34 | P a g e
Fundamentals of Programming II

Chapter Four:-Files
At the end of the chapter, students will be able to:
 Define file and file management
 Know streams and files:- Streams, files, The standard streams and C++ File I/O Classes
and functions
 Identify Text and Binary Files
 Know text file processing
 Know to open and close a file
 read and write text files, binary file processing
 identify get () and put (), read () and write (), More get () functions
 define random access files:- Obtaining the Current File Position, I/O Status
 know the meaning of buffers and synchronization in C++ programming
File
A logical collection of records where each record consists of a number of items known as fields”.
C++ provides some classes to perform output and input of characters to/from files
The information / data stored under a specific name on a storage device.
A storage unit on a computer that stores information, data, etc. (such as a document, an image,
etc.).
 Folders contain files
 Files have names and are represented by various icons
At the lowest level, a file in C++ is interpreted simply as a sequence of bytes.
The records in a file can be arranged in the following three ways:
 Ascending/Descending order: The records in the file can be arranged according to
ascending or descending order of a key field..
 Alphabetical order: If the key field is of alphabetic type then the records are arranged in
alphabetical order.
Chronological order: In this type of order, the records are stored in the order of their occurrence
i.e. arranged according to dates or events.
If the key-field is a date, i.e., date of birth, date of joining, etc. then this type of arrangement is
used.
In C++, a stream is a data flow from a source to a sink.

35 | P a g e
Fundamentals of Programming II

The sources and sinks can be any of the input/output devices or files.
For input and output, there are two different streams called input stream and output stream.
Stream Description
 Cin standard input stream
 Cout standard output stream
 Cerr standard error stream
The standard source and sink is keyboard and monitor screen respectively
ifstream: It is the input file stream class.
Its member function open ( ) associates the stream with a specified file in an input mode.
In addition to open (), ifstream class inherits the following functions from istream class.
(i) get( ) (ii) getline( ) (iii) read( ) (iv) seekg( ) (v) tellg( )
ofstream: It is the output file stream class.
Its member function open ( ) associates the stream with a specified file in an output mode.
In addition to open (), ofstream inherits the following functions from ostream class
(i) put ( ) (ii) write( ) (iii) seekp( ), (iv) tellp( )
fstream: It supports files for simultaneous input and output.
It is derived from ifstream, ofstream and iostream classes.
The functions associated with this stream are:
1. Open: This associates the stream with a specified file.
2. Close: It closes the stream.
3. Close all: It closes all the opened streams
4. seekg: Sets current `get' position in a stream
5. seekp: Sets current `put' position in a stream
6. tellg: Returns the current `get' position in a stream
7. tellp: Returns the current `put' position in a stream.
File Management System
 Used for file maintenance (or management) operations.
 It is a type of software that manages data files in a computer system.
 Has limited capabilities and is designed to manage individual or group files, such as
special office documents and records.

36 | P a g e
Fundamentals of Programming II

 It may display report details, like owner, creation date, state of completion and similar
features useful in an office environment.
 Also known as a file manager.
The system may contain features like:
 Assigning queued document numbers for processing.
 Owner and process mapping to track various stages of processing.
 Report generation, Notes, Status.
 Create, modify, move, copy, delete and other file operations, Add or edit basic metadata.
File Management: The process and act of creating an organized structure in which you store
information for easy retrieval.
Basics of File I/O
Accessing a binary file from a C++ program requires firstly attaching a stream variable to the
file. The usual stream classes’ ofstream (output file stream) and ifstream (input file stream) are
still the types of streams to use. An additional type called an fstream is provided which allows
for files that can be written to and read from if this is a desirable property.
Before any operation can take place on a file, it of course must be opened, and when you are
finished with the file, it should be closed to avoid loss of data.
General File I/O Steps
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the input/output sources.
4. Open the file
5. Use the file stream variables with >>, <<, or other input/output functions.
6. Close the file.
Using Input/Output Files
 stream - a sequence of characters (bytes)
 interactive (iostream)
 cin - input stream associated with keyboard.
 cout - output stream associated with display
o file (fstream)
 ifstream - defines new input stream (normally associated with a file).

37 | P a g e
Fundamentals of Programming II

 ofstream - defines new output stream (normally associated with a file).


Stream I/O Library Header Files
Note: There is no “.h” on standard header files : <fstream>
iostream -- contains basic information required for all stream I/O operations
fstream -- contains information for performing file I/O operations
Text file: It is a file that stores information in ASCII characters.
C++ Input and Output: Streams
Stream: the basic data type for input output in c++.
Stream classes are a Classes dealing with the input and output of data
C++ incorporates a complex hierarchy of stream types.
The most basic stream types are the standard input out streams:
Istream cin built-in input stream variable; by default hooked to keyboard
Ostream cout built-in output stream variable; by default hooked to console
C++ streams are objects.
The input and output streams, cin and cout are actually c++ objects.
Class: - a C++ construct that allows a collection of variables, constants and functions to be
grouped together logically under a single name.
Object: - a variable a type that is a class (often called an instance of the class)
For example, istream is actually a type name for a class.
Cin is the name of a variable of type istream.
So, cin is an instance or an object of the class istream.
A stream provides a connection between the process that initializes it and an object, such as a
file, which may viewed as a sequence of data.
Stream object is simply a serialized view of that other object.
Stream. It refers to a sequence of bytes.
A C++ stream is a flow of data into or out of a program, such as the data written to cout or read
from cin. For this class we are currently interested in four different classes:
istream is a general purpose input stream. cin is an example of an istream.
ostream is a general purpose output stream. cout and cerr are both examples of ostreams.
ifstream is an input file stream. It is a special kind of an istream that reads in data from a data
file.

38 | P a g e
Fundamentals of Programming II

ofstream is an output file stream. It is a special kind of ostream that writes data out to a data
file.

The ifstream Class


An ifstream is an input file stream, i.e. a stream of data used for reading input from a file.
Because an ifstream IS an istream, anything you can do to an istream you can also do the same
way to an ifstream.
In particular, cin is an example of an istream, so anything that you can do with cin you can also
do with any ifstream.
The use of ifstreams (and ofstreams ) requires the inclusion of the fstream header:
#include <fstream>
The ofstream Class
An ofstream is an output file stream, and works exactly like ifstreams, except for output instead
of input. Once an ofstream is created, opened, and checked for no failures, you use it just like
cout: ofstream fout( "outputFile.txt" );
fout << "The minimum oxygen percentage is " << minO2 << endl;
//Add additional header files you use
#include <fstream>
int main ()
{ /* Declare file stream variables such as
the following */
ifstream fsIn;//input
ofstream fsOut; // output
39 | P a g e
Fundamentals of Programming II

fstream both //input & output


//Open the files
fsIn.open("prog1.txt"); //open the input file
fsOut.open("prog2.txt"); //open the output file
//Code for data manipulation
//Close files
fsIn.close();fsOut.close();
return 0; }
Open ()
 Opening a file associates a file stream variable declared in the program with a physical file
at the source, such as a disk.
 In the case of an input file:
 The file must exist before the open statement executes.
 If the file does not exist, the open statement fails and the input stream enters the fail state
 An output file does not have to exist before it is opened;
 If the output file does not exist, the computer prepares an empty file for output.
 If the designated output file already exists, by default, the old contents are erased when
the file is opened.
 A file can be opened in C++ by two methods:
1. By using the constructor of the stream class to be used
2. By using the open ( ) function of the stream class to be used
File Open Mode
#include <fstream>
int main(void)
{
ofstream outFile("file1.txt", ios::out);
outFile << "That's new!\n";
outFile.close();
Return 0;
}
If you want to set more than one open mode, just use the OR operator- |. This way:

40 | P a g e
Fundamentals of Programming II

ios::ate | ios::binary
ofstream newfile;...(i)
newfile.open(“test.dat”);...(ii)
In the statement
(i) Declares the stream newfile to be of type ofstream i.e. output stream.
(ii) Assigns the file stream to the file called “test.dat”.
Thus, in the program the file “test.dat” would be known as newfile.
The major advantage of this method of opening a file is that more than one file can be opened at
a time in a program.
File I/O Example: Reading
Read char by char
#include <iostream>
#include <fstream>
int main()
{//Declare and open a text file
ifstream openFile(“data.txt");
char ch;
//do until the end of file
while( ! OpenFile.eof ())
{
OpenFile.get(ch); // get one character
cout << ch; // display the character
}
OpenFile.close(); // close the file
return 0;
}
Read a line
#include <iostream>
#include <fstream>
#include <string>
int main()

41 | P a g e
Fundamentals of Programming II

{//Declare and open a text file


ifstream openFile("data.txt");
string line;
While (! openFile.eof ())
{//fetch line from data.txt and put it in a string
getline(openFile, line);
cout << line;
}
openFile.close(); // close the file
return 0; }
For reading entire lines of text:
1. C++ provides get ( ) and getline( ) functions as input member functions of the ifstream class.
2. It also provides a put ( ) function as output member function of the ofstream class.
File I/O Example: Writing
 First Method (use the constructor)
#include <fstream>
using namespace std;
int main()
{/* declare and automatically open the file*/
ofstream outFile("fout.txt");
//behave just like cout put the word into the file
outFile << "Hello World!";
outFile.close();
return 0;
}
Second Method (use Open function)
#include <fstream>
using namespace std;
int main()
{// declare output file variable
ofstream outFile;

42 | P a g e
Fundamentals of Programming II

// open an exist file fout.txt


outFile.open("fout.txt”);
//behave just like cout, put the word into the file
outFile << "Hello World!";
outFile.close();
return 0;
}
File format
 In c++ files we (read from/ write to) them as a stream of characters
 Example writing to file
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream outFile;
// open an exist file fout.txt
outFile.open("number.txt",ios::app);
if (!outFile.is_open())
{ cout << " problem with opening the file ";}
else
{outFile <<200 <<endl ;
cout << "done writing" <<endl;}
outFile.close();
}
Example Reading from file
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

43 | P a g e
Fundamentals of Programming II

void main()
{//Declare and open a text file
ifstream INFile("number.txt");
string line;
int total=0;
while(! INFile.eof())
{
getline(INFile, line);//converting line string to int
stringstream(line) >> total;
cout << line <<endl;cout <<total +1<<endl;}
INFile.close(); // close the file
}
eof()
You can detect when the end of the file is reached by using the member function eof() which has

prototype :
It returns non-zero when the end of file has been reached, otherwise it returns zero.
For example, consider the following code fragment:
ifstream fin ;
fin.open("master", ios::in | ios::binary);
while(!find.eof()) //as long as eof() is zero
{ //that is, the file's end is not reached : //process the file }
if(fin.eof()) //if non-zero
cout << "End of file reached ! \n";
Text and Binary Files
Formatted input/output, character input/output, and string input/output functions can be used
only with text files.
Text files store data as a sequence of characters; binary files store data as they are stored in
primary memory.
Text file. It is a file that stores information in ASCII characters.

44 | P a g e
Fundamentals of Programming II

In text files, each line of text is terminated with a special character known as EOL (End of Line)
character or delimiter character. When this EOL character is read or written, certain internal
translations take place.
Binary file:- a file that contains information in the same format as it is held in memory.
In binary files, no delimiters are used for a line and no translations occur here.
Binary file is one in which data is stored in binary format, as opposed to a text file, which stores
data in ASCII format.
A binary file is more compact than a text file, and can therefore store data more efficiently.
For example, the integer value 12345 is 11000000111001 in binary.
Classes for file stream operation
 ofstream: Stream class to write on files
 ifstream: Stream class to read from files
 fstream: Stream class to both read and write from/to files.
 OPENING FILE USING CONSTRUCTOR
 ofstream outFile("sample.txt"); //output only
 ifstream inFile(“sample.txt”); //input only
 OPENING FILE USING open()
 Stream-object.open(“filename”, mode) ofstream outFile;
 outFile.open("sample.txt");
 ifstream inFile; inFile.open("sample.txt");

File mode parameter Meaning

ios::app Append to end of file

ios::ate go to end of file on opening

ios::binary file open in binary mode

ios::in open file for reading only

ios::out open file for writing only

ios::nocreate open fails if the file does not exist

45 | P a g e
Fundamentals of Programming II

ios::noreplace open fails if the file already exist

ios::trunc delete the contents of the file if it exist

All these flags can be combined using the bitwise operator OR (|).
For example, if we want to open the file example.bin in binary mode to add data we could do it
by the following call to member function open(): fstream file; file.open ("example.bin", ios::out |
ios::app | ios::binary);
 Closing File
 outFile.close();
 inFile.close();
 INPUT AND OUTPUT OPERATION
 put() and get() function
 The function put () writes a single character to the associated stream.
 Similarly, the function get () reads a single character form the associated stream.
 example :
 file.get(ch);
 file.put(ch);
 write() and read() function
 write() and read() functions write and read blocks of binary data.
 example:
 file.read((char *)&obj, sizeof(obj));
 file.write((char *)&obj, sizeof(obj));
Random File Access
Random access files permit nonsequential, or random, access to a file's contents.
To access a file randomly, you open the file, seek a particular location, and read from or write to
that file. An application can be created to access file information in a random fashion.
In a sequential file, information is accessed in a chronological order whereas the random access
provides instant fetching of a record and that too can in any order or no order at all.
In random access, we must implement the capability to locate a record immediately.
This is typical of any transaction system, be it banking, ticket reservation, and so forth.

46 | P a g e
Fundamentals of Programming II

The file manipulation functions, such as seekg and seekp, are used to position the get file-pointer
and put the file-pointer in a strategic location within the file, respectively.
For example, seekg sets the position of the next character to be extracted from the input stream
and seekp sets the position of the next character to be inserted into the output stream.
With random access to files, we can instantly retrieve and manipulate fixed-length records.
File Handling Functions
The ostream write function is used to write fixed number of bytes to a specified stream.
Here, the stream is associated with a file. The put file-position pointer decides the location of
where to write the data.
Similarly, the istream read function is used to read a fixed number of bytes from the specified
stream, which is a file in this case. The get file-position pointer determines the location in the file
to read from. The idea of opening the file in binary mode is that it is ideal for writing fixed-
length records.
put( ) and get( )
One way that you may read and write unformatted data is by using the member functions get( )
and put( ). These functions operate on characters.
That is, get( ) will read a character and put( ) will write a character. Of course, if you have
opened the file for binary operations and are operating on a char (rather than a wchar_t stream),
then these functions read and write bytes of data.
The get( ) function has many forms, but the most commonly used version is shown here along
with put( ):
istream &get(char &ch); ostream &put(char ch);
The get( ) function reads a single character from the invoking stream and puts that value in ch
and it returns a reference to the stream.
The put( ) function writes ch to the stream and returns a reference to the stream.
The following program displays the contents of any file, whether it contains text or binary data,
on the screen. It uses the get( ) function.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])

47 | P a g e
Fundamentals of Programming II

{char ch; if(argc!=2) {


cout << "Usage: PR <filename>\n";
return 1;
}ifstream in(argv[1], ios::in | ios::binary);
if(!in) { cout << "Cannot open file.";
return 1; }while(in) { // in will be false when eof is reached
in.get(ch); if(in) cout << ch; }return 0; }
As stated in the preceding section, when the end-of-file is reached, the stream associated with the
file becomes false.
Therefore, when in reaches the end of the file,it will be false, causing the while loop to stop.
There is actually a more compact way to code the
 read( ) and write( )
Another way to read and write blocks of binary data is to use C++'s read ( ) and write( )
functions.
Their prototypes are istream &read (char *buf, streamsize num);
ostream &write(const char *buf, streamsize num);
The read ( ) function reads num characters from the invoking stream and puts them in the buffer
pointed to by buf.
The write ( ) function writes num characters to the invoking stream from the buffer pointed to by
buf. streamsize is a type defined by the C++ library as some form of integer.

It is capable of holding the largest number of characters that can be transferred in any one I/O
operation.
The preceding program writes an array of floating-point values to disk and then reads them back.
After the call to read ( ), gcount( ) is used to determine how many bytes were just read.
More get ( ) Functions
The get( ) function is overloaded in several different ways.
The prototypes for the three most commonly used overloaded forms are shown here:
istream &get(char *buf, streamsize num);
istream &get(char *buf, streamsize num, char delim); int get( );
The first form reads characters into the array pointed to by buf until either num-1 characters have
been read, a newline is found, or the end of the file has been encountered.
48 | P a g e
Fundamentals of Programming II

The array pointed to by buf will be null terminated by get ( ).


If the newline character is encountered in the input stream, it is not extracted.
Instead, it remains in the stream until the next input operation.
The second form reads characters into the array pointed to by buf until either num-1 characters
have been read, the character specified by delim has been found.
The array pointed to by buf will be null terminated by get ( ).
If the delimiter character is encountered in the input stream, it is not extracted.
Instead, it remains in the stream until the next input operation.
The third overloaded form of get( ) returns the next character from the stream.
It returns EOF if the end of the file is encountered.
This form of get( ) is similar to C’s getc( ) function.
File Position Pointers
 Number of next byte to read/write
 Functions to reposition pointer
 seekg (seek get for istream class)
 seekp (seek put for ostream class)
 Classes have "get" and "put" pointers
 seekg and seekp take offset and reference position
 Offset: number of bytes relative to a reference position
 Reference positions (ios::beg default)
 ios::beg - relative to beginning of stream
 ios::cur - relative to current position
 ios::end - relative to end
 Examples:– fileObject.seekg(0)
 Goes to front of file (location 0) because ios::beg is default
 fileObject.seekg(n)
 Goes to nth byte from beginning
 fileObject.seekg(n, ios::cur)
 Goes n bytes forward
 fileObject.seekg(n, ios::end)
 Goes n bytes back from end

49 | P a g e
Fundamentals of Programming II

 fileObject.seekg(0, ios::end)
 Goes to last byte
 seekp similar
 To find pointer location:-tellg and tellp
 long location; location = fileObject.tellg()
 Example:- Assume you need to scan a file twice from the beginning
 //read file from beginning to EOF
 …
 // reset eofbit for next input
 file.clear();
 // move to beginning of file
 file.seekg( 0 );
 //read again file from beginning to EOF
Buffers and Synchronization
When we operate with file streams, these are associated to an internal buffer object of
type stream buf.
This buffer object may represent a memory block that acts as an intermediary between the stream
and the physical file.
For example, with an ofstream, each time the member function put (which writes a single
character) is called, the character may be inserted in this intermediate buffer instead of being
written directly to the physical file with which the stream is associated.
When the file is closed: before closing a file, all buffers that have not yet been flushed are
synchronized and all pending data is written or read to the physical medium.
When the buffer is full: Buffers have a certain size.
When the buffer is full it is automatically synchronized.
Explicitly, with manipulators: When certain manipulators are used on streams, an explicit
synchronization takes place. These manipulators are: flush and endl.
Explicitly, with member functions sync (): Calling the stream's member function sync () causes
an immediate synchronization.
This function returns an int value equal to -1 if the stream has no associated buffer or in case of
failure. Otherwise (if the stream buffer was successfully synchronized) it returns 0.

50 | P a g e

You might also like