Question: 4
Create a file store text into it, read the contents character by character and display the contents.
Sol:
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h> //gets()
#include<stdlib.h> //exit()
using namespace std;
void create()
{
ofstream abc;
char str[80],ch;
/* clrscr(); */
abc.open("hello");
if(abc.fail())
{
cout<<"unable to open the file"<<endl;
exit(1);
}
do
{
cout<<"Enter the text to store ";
fflush(stdin);
gets(str);
//cin.getline(str,80);
abc<<str<<endl;
cout<<"Would you like to cont.....";
fflush(stdin);
cin>>ch;
}while(ch=='y' || ch=='Y');
abc.close();
}
void display()
{
ifstream pqr;
char ch;
cout<<"The contents of the file are "<<endl;
pqr.open("hello");
if(pqr.fail())
{
cout<<"Unable to open the file"<<endl;
exit(1);//return;
}
while(!pqr.eof())
{
pqr.get(ch);
//cout<<ch;
cout.put(ch);
}
pqr.close();
}
int main()
{
create();
display();
return(0);
}
Question: 5
Write a function in c++ named count_alpha() to read a file named “article.txt”. Count and print total alphabets in the file.
Sol:
/* count total alphabet in the file */
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
void count_alpha()
{
ifstream pqr;
char ch;
int a=0;
pqr.open("article.txt");
if (pqr.fail())
{
cout<<"Unable to open the file"<<endl;
exit(1);
}
while(!pqr.eof())
{
pqr.get(ch);
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
a++;
cout.put(ch);
}
pqr.close();
cout<<"total alphabets = "<<a<<endl;
}
int main()
{
/* clrscr(); */
count_alpha();
return(0);
}
Question: 6
Write a function in c++ named count_lower() to read a file named “hello.txt”. Count and print total lower case alphabets in the file.
Sol:
/* count total lower case alphabet in the file */
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
void count_lower()
{
ifstream pqr;
char ch;
int a=0;
pqr.open("hello.txt");
if (pqr.fail())
{
cout<<"Unable to open the file"<<endl;
exit(1);
}
while(!pqr.eof())
{
pqr.get(ch);
if(ch>='a' && ch<='z')
a++;
cout.put(ch);
}
pqr.close();
cout<<"total lower case alphabets = "<<a<<endl;
}
int main()
{
/* clrscr(); */
count_lower();
return(0);
}




