0% found this document useful (0 votes)
91 views50 pages

Lab Manual Etcs204 Oops

The experiment details the program for multiplication of two matrices using object-oriented programming in C++. The program defines a matrix class with member variables to store the 2D array and its dimensions. Member functions are used to initialize the matrices by user input, perform multiplication, and display the result. The program demonstrates the use of classes, arrays, and basic OOP concepts in C++.

Uploaded by

Ansh Arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views50 pages

Lab Manual Etcs204 Oops

The experiment details the program for multiplication of two matrices using object-oriented programming in C++. The program defines a matrix class with member variables to store the 2D array and its dimensions. Member functions are used to initialize the matrices by user input, perform multiplication, and display the result. The program demonstrates the use of classes, arrays, and basic OOP concepts in C++.

Uploaded by

Ansh Arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

ETCS254

OBJECT ORIENTED PROGRAMMING


USING C++ LAB
LABORATORY MANUAL

Shri Vishwakarma Skill University


B. Tech. Computer Engineering

1
The document is for internal circulation only.

Copyright © 2024 Shri Vishwakarma Skill University

All rights reserved.

All materials on these pages are copyrighted by the Shri Vishwakarma Skill University. All rights reserved.
Reproduction, modification, retransmission, in any form or by any means, electronic, mechanical or
otherwise, for reasons other than personal use, is strictly prohibited without prior written permission.

First Edition
January,2024

Published by:
Shri Vishwakarma Skill University

2
PREFACE

The Department of Computer Science Engineering, Shri Vishwakarma Skill University has
prepared this laboratory manual. It is designed as the faculty an instruction book for purposes
listed in order of importance as follows:

1. To provide techniques, procedures and precautions related to the experiments.


2. To provide the laboratory safety and general rules and instructions.
3. To provide a general reference book that will give information which will assist in the
understanding of details about the laboratory and the experiment to be performed.

The manual is prepared with the idea that the revisions must be made periodically in order to
have the available text that represents the experiments. It has been tried to maintain the format
with diagrams, tables and illustrations.

It is believed that the information in the manual will enhance the practical skills of the students
along with developing the base of the subject.

Any suggestions and comments for further improvement of this manual will be gratefully
acknowledged.

Faculty
Shri Vishwakarma Skill University

3
Table of Contents
General Rules and Instructions:
Instruction for Students 5
General discipline in the Lab 5
Preparations and Performance 5
Lab Report 6
The lab report must contain the following: 6
List of Experiments
Experimental Setup Details
Experiment Details
Experiment No: 1
Experiment No: 2 13-15
Experiment No: 3 16-18
Experiment No: 4 19-24
Experiment No: 5 25-31
Experiment No: 6 32-34
Experiment No: 7 35-36
Experiment No: 8 37-41
Experiment No: 9 42-45
Experiment No: 10 46-49

4
General Rules and Instructions:
Instruction for Students

To complete all the experiments within time, to understand them completely and effectively, each student
must obey the following points:

General discipline in the Lab

Discipline is always given the highest precedence for maintaining the quality standard of your lab. Any
misconduct will be seriously dealt with and immediately responded without prior notification.
To ensure a pleasant, productive and comfortable experience for all of our users, you are directed to adhere
to the following guidelines:
 Students will not be allowed after ten minutes from the scheduled time.
 Students will not leave the lab till the period is over.
 Attendance in the lab class is compulsory.
 Students should maintain silence while performing the experiments.
 Students should not attend a different lab group/section other than the one assigned at the
beginning of the session.
 Please help us to keep the facility (Equipment’s- etc.) clean by discarding trash in the receptacles.
 Please respect the sensitivities of your peers and refrain from viewing any inappropriate content.
 Any attempt on Hacking information will be reciprocated with serious consequences.

Please abide by the rules and make appropriate use of all facilities. Users found to be damaging computer
configurations, accessing content or systems illegally or attempting to compromise security may be
deprived of the facility or will be fined.

Preparations and Performance


 Students should come to the lab thoroughly prepared on the experiments they are assigned to
perform on that day.
 Faculty may check their preparation and understanding of the experiments. If not found
satisfactory, students may be debarred from doing the experiments.
 Students should save the results (Screenshots) of their programs performed during lab session.
 Students must bring the lab manual on each practical class with Algorithm, Flowchart, Program and
Results (Screenshots) of the last experiments performed complete in all respect.
 Students without lab manual will not be allowed to do the experiments and hence lose their
attendance.

5
Lab Report

 Each student is required to write a complete report of the experiments, he has performed and
bring to lab class for evaluation in the next working lab.
 Report should be written very clearly and lab record should be maintained neatly.

The lab report must contain the following:

 Duly completed title page


 Theory/ Algorithms/ Flowcharts
 Code of Program
 Screenshots of Results

6
ETCS254: OBJECT ORIENTED PROGRAMMING USING C++ LAB
EVEN 2023-24

LIST OF EXPERIMENTS
Exp. Aim of the Experiment
No

1. Write a program for multiplication of two matrices using OOP.

2. Write a program to perform addition of two complex numbers using constructor


overloading. The first constructor which takes no argument is used to create objects which
are not initialized, second which takes one argument is used to initialize real and imag parts
to equal values and third which takes two argument is used to initialized real and imag to
two different values.

3. Write a program to find the greatest of two given numbers in two different classes using
friend function

4. Implement a class string containing the following functions: - Overload + operator to carry
out the concatenation of strings. - Overload = operator to carry out string copy. - Overload
<= operator to carry out the comparison of strings. - Function to display the length of a
string. - Function tolower( ) to convert upper case letters to lower case. - Function toupper(
) to convert lower case letters to upper case

5. Create a class called LIST with two pure virtual function store() and retrieve().To store a
value call store and to retrieve call retrieve function. Derive two classes stack and queue
from it and override store and retrieve. .

6. Write a program to define the function template for calculating the square of given numbers
with different data types.

7. Write a program to demonstrate the use of special functions, constructor and destructor in
the class template. The program is used to find the bigger of two entered numbers..

8. Write a program to perform the deletion of white spaces such as horizontal tab, vertical tab,
space, line feed, new line and carriage return from a text file and store the contents of the
file without the white spaces on another file.

9. Write a program to read the class object of student info such as name , age ,sex ,height and
weight from the keyboard and to store them on a specified file using read() and write()
functions. Again the same file is opened for reading and displaying the contents of the file
on the screen

10. Write a program to raise an exception if any attempt is made to refer to an element whose
index is beyond the array size.

NAME & SIGNATURE OF COURSE COORDINATOR

7
Experimental Setup Details

Software Requirements:
TurboC2.0/ Turbo C++3.0+/
Visual Studio code / any Online C++ compiler

Hardware Requirements:
No specific requirements. Any computer Hardware capable of running DOS can be used for this
course
Minimum Recommended: - i3 processor with 4 GB RAM, 80 GB HDD, Windows 8/10, Browser

8
Experiment Details

9
Experiment No: 1

Title: Write a program for multiplication of two matrices using OOP.


Objective: To study the class, array, objects and I/O files.
Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO1- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include<iostream.h>
class matrix
{
int **a,l1,l2;
public:
void initialize_matrix(int m,int n)
{
l1=m;
l2=n;
a = new int*[m];
for(int p=0;p<m;p++)
{
a[p] = new int[n];
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=0;
}
}
}

void display_matrix()
{
for(int i=0;i<l1;i++)
{
cout<<" ";
for(int j=0;j<l2;j++)
{
cout<<a[i][j]<<"";
}
cout<<"\n";
}
}

10
void enter_matrix()
{
for(int i=0;i<l1;i++)
{
for(int j=0;j<l2;j++)
{
cin>>a[i][j];
}
}
}

int multiply_matrix(matrix m1, matrix m2)


{
if(m1.l2!=m2.l1)
{
cout<<"\n\n Matrix multiplication not possible\n";
return 0;
}
else
{
for(int i=0;i<m1.l1;i++)
{
for(int j=0;j<m2.l2;j++)
{
for(int k=0;k<m1.l2;k++)
{
a[i][j]+=m1.a[i][k]*m2.a[k][j];
}
}
}
return 1;
}
}
};
int main()
{
cout<<"\n ----------------------------------------------------";
cout<<"\n\n Multiplication of two matrices using C++";
cout<<"\n ----------------------------------------------------";
matrix m1,m2,m3;
int row1,col1,row2,col2;
cout<<"\n you can enter with space separation or Enter key press-";
cout<<"\n\n Enter the rows and columns of first matrix - ";
cin>>row1>>col1;
m1.initialize_matrix(row1,col1);
cout<<"\n Enter the rows and columns of second matrix - ";
cin>>row2>>col2;
m2.initialize_matrix(row2,col2);
cout<<"\n Enter the elements of first matrix - ";
m1.enter_matrix();
cout<<"\n Enter the elements of second matrix - ";
m2.enter_matrix();

11
cout<<"\n First Matrix - \n\n";
m1.display_matrix();
cout<<"\n Second Matrix - \n\n";
m2.display_matrix();
cout<<"\n\n Multiplying both matrices...";
m3.initialize_matrix(row1,col2);
if(m3.multiply_matrix(m1,m2))
{
cout<<"\n\n Resultant matrix - \n\n";
m3.display_matrix();
}

return 0;
}

Sample Output:

Suggestive Readings:
● www.geeksforgeeks.org/object-oriented-programming-in-cpp/

● https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm

12
Experiment No: 2

Title: Write a program to perform addition of two complex numbers using constructor
overloading. The first constructor which takes no argument is used to create objects
which are not initialized, second which takes one argument is used to initialize real and
imag parts to equal values and third which takes two argument is used to initialized real
and imag to two different values. .
Objective: To study the basic programming using c++ for the complex no

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO1- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

class complexno

int real,imag;

public:

complexno()

real=0;

imag=0;

complexno(int i)

real=i;

imag=i;

complexno(int a,int b)

real=a;

imag=b;

13
}

void add(complexno c1, complexno c2)

real = c1.real+c2.real;

imag = c1.imag+c2.imag;

void display()

cout<<real<<"+"<<imag<<"i";

};

#include<iostream.h>

int main()

{ cout<<"\n\n Program to perform addition of two complex numbers using constructor


overloading";

int real,imag;

cout<<"\n Enter a single value for real and imaginary parts of first complex number : ";

cin>>real;

complexno c1(real);

cout<<"\n First complex number is given by - ";

c1.display();

cout<<"\n\n Enter different values for real and imaginary parts of second complex
number : ";

cin>>real>>imag;

complexno c2(real,imag);

cout<<"\n Second complex number is given by - ";

c2.display();

complexno c3;

cout<<"\n\n Initially third complex number is - ";

14
c3.display();

cout<<"\n\n Storing the result of addition of first and second complex number into
third...";

c3.add(c1,c2);

cout<<"\n\n Now third complex number is given by - ";

c3.display();

cout<<"\n";

return 0;

Sample Output:

15
Experiment No: 3

Title: Write a program to find the greater of two given numbers in two different classes
using friend function.
Objective: To study the use of friend function

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO3- Solve basic problems using concepts of multiple class use, function in object-
oriented programming.

Code/Algorithm/Theory:
Source Code:

#include<iostream.h>

class a;

class b

int number;

public:

b(int x)

number=x;

void friend greatest(a a1,b b1);

};

class a

int number;

public:

a(int x)

number=x;

16
}

void friend greatest(a a1,b b1);

};

void greatest(a a1,b b1)

if(a1.number>b1.number)

cout<<"\n Number in class A is greatest i.e. "<<a1.number;

else if(a1.number<b1.number)

cout<<"\n Number in class B is greatest i.e. "<<b1.number;

else

cout<<"\n Number in both classes are equal";

int main()

cout<<"\n\n Program to find greatest of two numbers in two different classes using
friend function";

cout<<"\n “______________________________________________________________________";

int num;

cout<<"\n\n Enter number for class A - ";

cin>>num;

a a1(num);

cout<<"\n Enter number for class B - ";

cin>>num;

17
b b1(num);

greatest(a1,b1);

cout<<"\n";

return 0;

Sample Output:

Experiment No: 4

18
Title: Implement a class string containing the following functions: - Overload + operator to
carry out the concatenation of strings. - Overload = operator to carry out string copy. -
Overload <= operator to carry out the comparison of strings. - Function to display the length of
a string. - Function tolower( ) to convert upper case letters to lower case. - Function toupper( )
to convert lower case letters to upper case
Objective: To study string operation in C++
Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO3- Solve basic problems using concepts of multiple class use, function in object-
oriented programming.

Code/Algorithm/Theory:
Source Code:

#include<iostream>

#include<string.h>

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

using namespace std;

class String

char *s;

int size;

public:

String(char *c)

size = strlen(c);

s = new char[size];

strcpy(s,c);

19
char* operator +(char *s1)

size = strlen(s)+strlen(s1);

char *s2 = new char[strlen(s)];

strcpy(s2,s);

s = new char[size];

strcpy(s,s2);

strcat(s,s1);

return s;

char* operator =(char *s1)

size = strlen(s1);

s = new char[size];

strcpy(s,s1);

return s;

bool operator <=(char *s1)

return strcmp(s,s1);

void display()

cout<<"\n\n String stored in class = "<<s;

void displaylength()

20
{

cout<<"\n\n Length of string stored in class = "<<size;

void Tolower()

cout<<"\n\n String converted to lowercase";

for(int i=0;i<size;i++)

if(isupper(s[i]))

s[i] = (char)tolower(s[i]);

display();

void Toupper()

cout<<"\n\n String converted to uppercase";

for(int i=0;i<size;i++)

if(islower(s[i]))

s[i] = (char)toupper(s[i]);

display();

};

int main()

char *s1;

int choice,l1;

21
cout<<"\n\n Program to perform operations on string";

cout<<"\n _____________________________________________________";

cout<<"\n\n Enter length of string - ";

cin>>l1;

fflush(stdin);

s1 = new char[l1];

cout<<"\n Enter string to be stored in class - ";

gets(s1);

String s(s1);

while(1)

char *d;

int length;

system("cls");

cout<<"\n\n Menu\n ____ \n 1. String concatenation \n 2. String copy \n 3.


String comparison \n 4. Display String \n 5. Display length of string \n 6. Convert
string to lowercase \n 7. Convert string to uppercase \n 8. Exit ";

cin>>choice;

if(choice==1)

s=s1;

cout<<"\n\n Enter the length of new string - ";

cin>>length;

d = new char[length];

fflush(stdin);

cout<<"\n Enter the string - ";

gets(d);

s = s+d;

cout<<"\n After concatenation....";

s.display();

22
else if(choice==2)

cout<<"\n\n Enter the length of new string - ";

cin>>length;

d = new char[length];

fflush(stdin);

cout<<"\n Enter the string - ";

gets(d);

s=d;

cout<<"\n After copying....";

s.display();

else if(choice==3)

cout<<"\n\n Enter the length of new string - ";

cin>>length;

d = new char[length];

fflush(stdin);

cout<<"\n Enter the string - ";

gets(d);

if(!(s<=d))

cout<<"\n Strings are equal";

else

cout<<"\n Strings are not equal";

else if(choice==4)

23
{

s.display();

else if(choice==5)

s.displaylength();

else if(choice==6)

{ s.Tolower(); }

else if(choice==7)

{ s.Toupper(); }

else if(choice==8)

{ exit(0); } else

{ cout<<"\n\n Wrong choice"; }

getch();

return 0;

Sample Output:

24
Experiment No: 5

Title: Create a class called LIST with two pure virtual function store() and retrieve().To
store a value call store and to retrieve call retrieve function. Derive two classes stack and
queue from it and override store and retrieve. .
Objective: To study the stack, queue and retrieval

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO4- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;

struct node
{
int data;
node *next;
};

node *head=NULL,*tail=NULL;

class List
{
public:
void view()
{
node *n = head;
if(head==NULL)
{
cout<<"\n No elements found...";
}
else
{
cout<<" ";
while(n!=NULL)
{
if(n->next==NULL)
{
cout<<n->data;
}

25
else
{
cout<<n->data<<"->";
}
n = n->next;
}
}
}
virtual void store(int n)=0;
virtual int retrive()=0;
};

class Stack :public List


{
public:
void store(int n)
{
node *n1 = new node();
n1->data = n;
n1->next=NULL;
if((head==NULL)&&(tail==NULL))
{
head = n1;
tail = n1;
}
else
{
tail->next = n1;
tail = n1;
}
}
int retrive()
{
if((tail==NULL)&&(head==NULL))
{
return -1;
}
else
{
int n = tail->data;
node *n1 = head;
while((n1->next!=tail)&&(head!=tail))
{
n1 = n1->next;
}
n1->next = NULL;
free(tail);
if(head!=tail)
{
tail = n1;
}
else

26
{
tail=NULL;
head=NULL;
}
return n;
}
}
};

class Queue:public List


{
public:
void store(int n)
{
node *n1 = new node();
n1->data = n;
n1->next=NULL;
if((head==NULL)&&(tail==NULL))
{
head = n1;
tail = n1;
}
else
{
tail->next = n1;
tail = n1;
}
}
int retrive()
{
if((tail==NULL)&&(head==NULL))
{
return -1;
}
else
{
int n = head->data;
if(head==tail)
{
head = tail = NULL;
}
else
{
head = head->next;
}
return n;
}
}
};

int main()
{

27
Stack s1;
int ch;
while(1)
{
system("cls");
cout<<"\n\n Program to implement stack and queue using pure virtual functions
store and retrieve";
cout<<"\n ________________________________________________________________________";
cout<<"\n\n Menu";
cout<<"\n ^^^^";
cout<<"\n\n 1. Stack";
cout<<"\n 2. Queue";
cout<<"\n 3. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch;
if(ch==1)
{
Stack s1;
int ch1;
while(1)
{
system("cls");
cout<<"\n\n Stack Menu";
cout<<"\n ^^^^^ ^^^^";
cout<<"\n 1. Push Element";
cout<<"\n 2. Pop Element";
cout<<"\n 3. View Stack";
cout<<"\n 4. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch1;
if(ch1==1)
{
int element;
cout<<"\n Enter the element you want to push - ";
cin>>element;
s1.store(element);
cout<<"\n Element Pushed";
}
else if(ch1==2)
{
int element=0;
element = s1.retrive();
if(element==-1)
{
cout<<"\n Stack is Empty";
}
else
{
cout<<"\n Element Popped = "<<element;
}
}
else if(ch1==3)

28
{
cout<<"\n Elements in stack from bottom to top:- ";
s1.view();
}
else if(ch1==4)
{
break;
}
else
{
cout<<"\n\n Wrong choice";
}
getch();
}
}
else if(ch==2)
{
Queue q1;
int ch1;
while(1)
{
system("cls");
cout<<"\n\n Queue Menu";
cout<<"\n -------------------";
cout<<"\n 1. Push Element";
cout<<"\n 2. Pop Element";
cout<<"\n 3. View Queue";
cout<<"\n 4. Exit";
cout<<"\n\n Enter your choice - ";
cin>>ch1;
if(ch1==1)
{
int element;
cout<<"\n Enter the element you want to push - ";
cin>>element;
q1.store(element);
cout<<"\n Element Pushed";
}
else if(ch1==2)
{
int element=0;
element = q1.retrive();
if(element==-1)
{
cout<<"\n Queue is Empty";
}
else
{
cout<<"\n Element Popped = "<<element;
}
}
else if(ch1==3)

29
{
cout<<"\n Elements in queue from front to rear:- ";
q1.view();
}
else if(ch1==4)
{
break;
}
else
{
cout<<"\n\n Wrong choice";
}
getch();
}
}
else if(ch==3)
{
exit(0);
}
else
{
cout<<"\n\n Wrong Choice";
}
getch();
}
return 0;
}
Sample Output:

30
31
Experiment No: 6

Title: Write a program to define the function template for calculating the square of given
numbers with different data types.
Objective: To study function template in c++

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO4- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include <iostream>

using namespace std;

template <class T>

inline T square(T x)

T result;

result = x * x;

return result;

};

int main()

{ int i, ii;

float x, xx;

double y, yy;

i = 2;

x = 2.2;

y = 2.2;

ii = square<int>(i);

cout << i << ": " << ii << endl;

32
xx = square<float>(x);

cout << x << ": " << xx << endl;

// Explicit use of template

yy = square<double>(y);

cout << y << ": " << yy << endl;

// Implicit use of template

yy = square(y);

cout << y << ": " << yy << endl; return 0;

Another Code 2
#include<iostream>

using namespace std;

template <class T>

T square(T num)
{
return num * num;
}

int main()
{
int int_num;
float float_num;

cout << "Enter a integer number:\t";


cin >> int_num;
cout << "Squared integer number:\t" << square(int_num) << endl;

cout << "Enter a floating-point number:\t";


cin >> float_num;
cout << "Squared floating-point number:\t" << square(float_num)
<< endl;
}

OUTPUT

33
34
Experiment No: 7

Title: Write a program to demonstrate the use of special functions, constructor and
destructor in the class template. The program is used to find the bigger of two entered
numbers..
Objective: To study constructor in C++

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO5- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include <iostream>

using namespace std;

template <class T>

T Large(T n1, T n2)

return (n1 > n2) ? n1 : n2;

int main()

int i1, i2;

float f1, f2;

char c1, c2;

cout << "Enter two integers:\n";

cin >> i1 >> i2;

cout << Large(i1, i2) <<" is larger." << endl;

35
cout << "\nEnter two floating-point numbers:\n";

cin >> f1 >> f2;

cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";

cin >> c1 >> c2;

cout << Large(c1, c2) << " has larger ASCII value.";

return 0;

Output:

36
Experiment No: 8

Title: Write a program to perform the deletion of white spaces such as horizontal tab,
vertical tab, space, line feed, new line and carriage return from a text file and store the
contents of the file without the white spaces on another file.
Objective: To study files

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO5- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
There are six types of whitespace characters by default:

1. Space (' ') - Space is the most common whitespace character. It is usually used to
separate two words.

2. Line feed ('\n') - The line feed character moves the cursor to the next line. It
signifies the end of a line of text.

3. Horizontal tab ('\t') - A horizontal tab moves the cursor to the next tab stop. It is
usually used for indentation purposes.

4. Vertical tab ('\v') - A vertical tab moves the cursor to the next vertical tab stop. It is
an outdated whitespace character and is rarely used anymore.

5. Carriage return ('\r') - The carriage return character is used to reset the cursor's
position to the start of a line of text.

6. Form feed ('\f') - A form feed is a page break character. It is used to end the

Source Code:

#include <iostream>

#include <algorithm>

#include <cctype>

#include <string>

int main(){

// Creating a string containing multiple whitespaces.

std::string s = "\tHello \n World";

std::cout << "String s before removing whitespaces: " << s << std::endl << std::endl;

37
// Using the erase, remove_if, and ::isspace functions.

s.erase(std::remove_if(s.begin(), s.end(), ::isspace),

s.end());

std::cout << "String s after removing whitespaces: " << s;

return 0;

#include <iostream>

#include <algorithm>

#include <locale>

#include <functional>

#include <string>

int main() {

// Creating a string.

std::string s = "\nWhitespace \t String\f";

std::cout << "String s before removing whitespaces: " << s <<

std::endl;

// Using the erase, remove_if, bind, and std::isspace functions.

s.erase(std::remove_if(s.begin(), s.end(), std::bind(std::isspace < char > ,

std::placeholders::_1,

std::locale::classic())),

s.end());

std::cout << "String s after removing whitespaces: " << s;

38
return 0;

}
OUTPUT :
String s before removing whitespaces:
Whitespace String
String s after removing whitespaces: WhitespaceString
#include <iostream>

#include <string>

#include <algorithm>

// Function that returns true if a character is a whitespace.

bool isWhitespace(unsigned char c) {

if (c == ' ' || c == '\t' || c == '\n' ||

c == '\r' || c == '\f' || c == '\v') {

return true;

} else {

return false;

int main() {

std::string s = "\nWhitespace \t String ";

std::cout << "String s before removing whitespaces: " << s <<

std::endl << std::endl;

// Using the isWhitespace function we created.

s.erase(std::remove_if(s.begin(), s.end(), isWhitespace), s.end());

std::cout << "String s after removing whitespaces: " << s;

39
return 0;

#include <iostream>

#include <string>

#include <algorithm>

int main() {

std::string s = "\rWhitespace String ";

std::cout << "String s before removing whitespaces: " << s <<

std::endl << std::endl;

// Removing whitespaces from string s.

s.erase(std::remove_if(s.begin(), s.end(),

[](char c) { // a lambda function

return (c == ' ' || c == '\n' || c == '\r' ||

c == '\t' || c == '\v' || c == '\f');

}),

s.end());

std::cout << "String s after removing whitespaces: " << s;

return 0;

Output:-

String s before removing whitespaces: Whitespace String

String s after removing whitespaces: WhitespaceString

40
we can use the std::regex_replace function to remove whitespace from a
string in C++. This function replaces all matching characters in a string
with the character specified by the user
#include<iostream>
#include <string>
#include <regex>

int main() {
std::string s = "Using \n\t Regex To \f Remove Whitespaces";

std::cout << "String s before removing whitespaces --> " << s <<
std::endl << std::endl;

// Defining a regular expression.


std::regex r("\\s+");

// Using the regular expression to remove whitespaces.


s = std::regex_replace(s, r, "");

std::cout << "String s after removing whitespaces --> " << s;


String s before removing whitespaces --> Using
Regex To Remove Whitespaces

String s after removing whitespaces --> UsingRegexToRemoveWhitespaces

/* Write a program to perform the deletion of white spaces such as horizontal tab,
vertical tab, space, line feed, new line and carriage return from a text file and store
the contents of the file without the white spaces on another file.

*/ #include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main() {

ifstream inputFile("input.txt");

ofstream outputFile("output.txt");

if (inputFile.is_open() && outputFile.is_open()) {

string line;

while (getline(inputFile, line)) {

for (char& c : line) {

if (!isspace(c)) {

outputFile << c;

41
inputFile.close();

outputFile.close();

cout << "White spaces removed and content saved to output.txt" << endl;

else {

cout << "Error opening files" << endl;

} return 0;

Output :

42
Experiment No: 9

Title: Write a program to read the class object of student info such as name ,
age ,sex ,height and weight from the keyboard and to store them on a specified file using
read() and write() functions. Again the same file is opened for reading and displaying the
contents of the file on the screen
Objective: To study how to write class data in files input / read and write operations

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO5- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include <iostream>
#include <fstream>
using namespace std;
// Class to define the properties
class Student {
public:
string Name;
int age;

43
string sex;
string height;
int weight;
};
int main(){
Student Stud_1;
Stud_1.Name="RANJEET";
Stud_1.age=43;
Stud_1.sex="Male";
Stud_1.height="5.5inch";
Stud_1.weight=65;

//Wriring this data to txt file


ofstream file1;
file1.open("Studfile.txt", ios::app);
file1.write((char*)&Stud_1,sizeof(Stud_1));
file1.close();
//Reading data from txt file
ifstream file2;
file2.open("Studfile.txt",ios::in);
file2.seekg(0);
file2.read((char*)&Stud_1,sizeof(Stud_1));
printf("\nName :%s",Stud_1.Name);
printf("\nAge :%d",Stud_1.age);
printf("\nSex :%s",Stud_1.sex);
printf("\nHeight:%s",Stud_1.height);
printf("\nWeight:%d",Stud_1.weight);
file2.close();
return 0;
}
Output:

Another Example //C++ program to write and read object using read and write function.
#include <iostream>
#include <fstream>

using namespace std;

44
//class student to read and write student details
class student
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}

void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};

int main()
{
student s;

ofstream file;

//open file in write mode


file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;

//write into file


s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file

file.close(); //close the file


cout<<"\nFile saved and closed succesfully."<<endl;

//re open file in input mode and read data


//open file1
ifstream file1;
//again open file in read mode
file1.open("aaa.txt",ios::in);
if(!file1){
cout<<"Error in opening file..";
return 0;
}
//read data from file
file1.read((char*)&s,sizeof(s));

45
//display data on monitor
s.showData();
//close the file
file1.close();

return 0;
}

46
Experiment No: 10

Title: Write a program to raise an exception if any attempt is made to refer to an element
whose index is beyond the array size.
Objective: To study exception handling in c++

Pre-requisites:
To be familiar with the basic concepts of C and C++ programming

Targeted CO:
CO5- Solve basic problems using concepts of object-oriented programming.

Code/Algorithm/Theory:
Source Code:

#include <iostream>
#include <array>
#include <exception>

using namespace std;

template<class T, int N>


void PrintArray(array<T, N> a)
{
for (int i = 0; i < int(a.size()); i++)
{
cout << a[i] << ' '; a[i] = 1 + i;
}
}

int main()
{
array <int, 6> arr = { 1,2,3,4,5,6 };
PrintArray<int, 6>(arr);

cout << " 2a pos do arr -> ";


cout << arr[2] ;

cout <<"if out of range given arr[7] then printing garbage not in range" ;
cout<<arr[7] ;

47
system("Pause");
return 0;

Output:

Another example
#include <iostream>
using namespace std;

int main() {

double numerator, denominator, arr[4] = {0.0, 0.0, 0.0, 0.0};


int index;

cout << "Enter array index: ";


cin >> index;

try {

// throw exception if array out of bounds


if (index >= 4)
throw "Error: Array out of bounds!";

// not executed if array is out of bounds


cout << "Enter numerator: ";

48
cin >> numerator;

cout << "Enter denominator: ";


cin >> denominator;

// throw exception if denominator is 0


if (denominator == 0)
throw 0;

// not executed if denominator is 0


arr[index] = numerator / denominator;
cout << arr[index] << endl;
}

// catch "Array out of bounds" exception


catch (const char* msg) {
cout << msg << endl;
}

// catch "Divide by 0" exception


catch (int num) {
cout << "Error: Cannot divide by " << num << endl;
}

// catch any other exception


catch (...) {
cout << "Unexpected exception!" << endl;
}

return 0;

49
}

50

You might also like