Oop CH5-1
Oop CH5-1
2. istream and ostream serves the base classes for iostream class. The class
istream is used for input and ostream for the output.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstreambase and from the corresponding
iostream class and they are designed specifically to manage disk files.
Opening a File
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.
1 open() function
Syntax
Here, the first argument of the open function defines the name and format of the file
with the address of the file.
The second argument represents the mode in which the file has to be opened.
Example
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a
class so we need to create an object of this class to use its member functions. So we
create new_file object and call open() function. Here we use out mode that allows us
to open the file to write in it.
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
Example
ofstream new_file;
As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the
file.
Using a stream insertion operator << we can write information to a file and using
stream extraction operator >> we can easily read information from a file.
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Output:
Explanation
In the above example we first create an object to class fstream and name it ‘new_file’.
Then we apply the open() function on our ‘new_file’ object. We give the name
‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which allows
us to write in our file. We use a ‘if’ statement to find if the file already exists or not if
it does exist then it will going to print “File creation failed” or it will gonna create a
new file and print “New file created”.
Writing to a File
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to
file
new_file.close();
}
return 0;
}
Output:
Explanation
Here we first create a new file “new_file_write” using open() function since we wanted
to send output to the file so, we use ios::out. As given in the program, information
typed inside the quotes after Insertion Pointer “<<” got passed to the output file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while
(!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
Output:
Explanation
In this example, we read the file that generated id previous example i.e.
new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we
print the content of the file using extraction operator >>. The output prints without
any space because we use only one character at a time, we need to use getline() with
a character array to print the whole line as it is.
Moving on with this article on File Handling in C++
Close a File
It is simply done with the help of close() function.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Output:
C++ Templates
Templates can be represented in two ways:
o Function templates
o Class templates
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type
as a parameter so that we don’t need to write the same code for different data types. For
example, a software company may need to sort() for different data types. Rather than writing
and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.
Using templates, it is possible to create generic functions and classes. In a generic function or
class, the type of data upon which the function or class operates is specified as a parameter.
Thus, you can use one function or class with several different types of data without having to
explicitly recode specific versions for each data type. Templates are sometimes called
parameterized classes or functions.
C++ adds two new keywords to support templates: ‘template’ and ‘type name’. The second
keyword can always be replaced by the keyword ‘class’.
Function Template
● Generic functions use the concept of a function template. Generic functions define a set
of operations that can be applied to the various types of data.
● The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
● For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.
● A Generic function is created by using the keyword template. The template defines what
function will do.
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Output
7
7
g
Example: WAP for swapping of two numbers using function template and display result
#include <iostream>
using namespace std;
template<class T> void swapValues(T &variable1, T &variable2)
{
T temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
int main()
{
int n1= 1, n2 = 2;
cout << “Original integer values are “<< n1 << “ “ << n2 << endl;
swapValues(n1, n2);
cout << “Swapped integer values are “ << n1 << “ “ << n2 << endl;
char c1 = ‘A’;
char c2 = ‘B’;
cout << "Original character values are: " << c1 << " " << cl2 << endl;
swapValues(c1, c2);
cout << "Swapped character values are: " << c1 << " " << c2;
return 0;
}
Example: Display value of passed variable using function template.
#include <iostream>
using namespace std;
template<class X> void display(X a,X b)
{
cout<<"\n Value of first variable="<<a;
cout<<"\n Value of second variable="<<b;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
display(i,j);
display(m,n);
return 0;
}
Output:
Value of first variable=2
Value of second variable=3
Value of first variable=2.3
Value of second variable=1.2
Example 3. This is a function template that prints the contents of the array
template<class T>
void printArray(const T*array, const int count)
{
for (int j = 0; j < count; j++)
cout << array[j] << “ “;
cout << endl;
}
This function will work on arrays of any class type when an appropriate insertion operator << has
been defined
int main()
{
const int aCount = 5;
const int bCount = 7;
const int cCount = 6;
int a[aCount] = {1, 2, 3, 4, 5};
double b[bCount] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[cCount] = “HELLO”;
cout << “Array a contains: “ << endl;
printArray(a, aCount);
cout << “Array b contains: “ << endl;
printArray(b, bCount);
cout << “Array c contains: “ << endl;
printArray(c, cCount);
return 0;
}
Syntax
Simple program:
#include <iostream>
using namespace std;
template <class type1, class type2>
void myfunc(type1 x, type2 y)
{
cout << x << ' ' << y << '\n';
}
int main()
{
myfunc(10, "I like C++");
myfunc(98.6, 19L);
return 0;
}
Using function template, we write code once and use it for any data type including user
defined
data types. For example, sort() can be written and used to sort any data type items. What if
we
want a different code for a particular data type? Is it possible to use different code only when
sort() is called for char data type?
It is possible in C++ to get a special behavior for a particular data type (here for char say for
example). This is called template specialization.
To denote the explicit specialization of a function, we need to mention that particular data
type
explicitly.
Syntax:
template < > ret-type func- name(specificdatatype parameter list)
{
// body of function
}
Example program for Function template specialization:
For example, consider the following simple code where we have general template fun() for
all
data types except int. For int, there is a specialized version of fun().
#include <iostream>
using namespace std;
template <class T> void fun(T a)
{
cout << "The main template fun(): " << a << endl;
}
template< > void fun(int a)
{
cout << "Specialized Template for int type: " << a << endl;
}
int main()
{
fun('a');
fun(10);
fun(10.14);
}
Output:
The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14
Experiment No 10 :
Exp 10 : 1. C++ program to find the sum of array elements using a function template:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "The sum of the elements of the array is: " << sum(arr, n) << endl;
return 0;
}
Exp 10-2 Write a C++ Program of Square Function using template specialization
● calculate the square of integer no. and a string. (Square of string is nothing
but Concatenation of a string with itself).
// template specialization
template <> string square<string>(string ss)
{
return (ss+ss);
};
int main()
{
int i = 2, ii;
string ww("Aaa");
ii = square<int>(i);
cout << i << ": " << ii << endl;
OUTPUT:
2: 4
AaaAaa
Class Template:
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.
Class Templates like function templates, class templates are useful when a class defines
something that is independent of the data type.
The general form of a generic class declaration is shown here:
template <class X> class Classname
{
//body of class
};
Ttype is a placeholder name which will be determined when the class is instantiated. We can define
more than one generic data type using a comma-separated list. The Ttype can be used inside the class
body.
Instance: class_name<type> ob;
};
int main()
{
A <int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2 : 11
Class Template with multiple generic types:
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Experiment No 10 :
c) C++ Program to build Simple calculator using Class template
#include <iostream>
using namespace std;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
return 0;
}
OUTPUT :
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2