C++ Programming
Slip18
Q.1) Write a C++ program to create a class Integer. Write necessary member functions to
overload the operator unary pre and post increment ‘ ++’ for an integer number.
[Marks 15]
Solution
#include<iostream.h>
#include<conio.h>
class integer
{
int no;
public:
integer(int x)
{
no=x;
}
integer operator ++(int n)
{
cout<<"Increament"<<endl;
n=this->no++;
return n;
}
integer operator ++()
{
cout<<"Increament"<<endl;
++this->no;
return 0;
}
void display()
{
cout<<"Result : "<<no<<endl;
}
};
int main()
{
int no1,no2;
cout<<"Enter number: ";
cin>>no1;
cout<<"\nEnter number: ";
cin>>no2;
integer n1(no1);
integer n2(no2);
n1++;
n1.display();
++n2;
n2.display();
getch();
return 0;
}
Output
Enter number: 5
Enter number: 7
Increament
Result : 6
Increament
Result : 8
Q.2) Write a C++ program to read the contents of a text file. Count and display number of
characters, words and lines from a file. Find the number of occurrences of a given word
present in a file. [Marks 25]
Solution
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<process.h>
int main()
{
fstream inf;
inf.open("D:/t1.txt",ios::in);
if(!inf.good())
{
cout<<"\n\tError in openning file";
getch();
exit(0);
}
int c=0,w=0,l=0,count = 0;
int flag = 0;
char ch;
int pos = 0;
char arr[50],search[50];
cout<<"\n\tEnter string to search:";
cin>>search;
while(inf)
{
inf.get(ch);
cout<<ch;
if(ch == ' ' && flag == 0)
{
w++;
flag = 1;
arr[pos] = '\0';
if(strcmp(arr,search) == 0)
count++;
pos = 0;
}
else if(ch == '\n')
{
l++;
flag = 0;
arr[pos] = '\0';
if(strcmp(arr,search) == 0)
count++;
pos = 0;
}
else
{
c++;
arr[pos++] = ch;
flag = 0;
}
}
cout<<"\n\t No of characters:"<<c;
cout<<"\n\t No of lines:"<<l;
cout<<"\n\t No of words:"<<w;
cout<<"\n\t No of occurrences of "<<
search<<" = "<<count;
getch();
return 0;
}
Tags:
c++