Question:10
Write a function in c++ named count_space() to read a file named “article.txt”. Count and print total spaces in the file.
Sol:
/* count total spaces in the file */ #include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> #include<stdlib.h> using namespace std; void count_spaces() { ifstream pqr; char ch; int s=0; pqr.open("article.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; getch(); exit(1); } while(!pqr.eof()) { pqr.get(ch); if(ch==' ') s++; cout.put(ch); } pqr.close(); cout<<"total spaces = "<<s<<endl; } int main() { count_spaces(); return(0); }
Question:11
Write a function in c++ named count() to read a file named “article.txt”. Count and print the following:
Total alphabets
Total upper case alphabets
Total lower case alphabets
Total digits
Total spaces
Total length of the file (total characters)
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> #include<stdlib.h> using namespace std; void count() { ifstream pqr; char ch; int c=0,a=0,ua=0,la=0,d=0,sp=0,spl=0; pqr.open("article.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; getch(); exit(1); } while(!pqr.eof()) { pqr.get(ch); if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')) { a++; if(ch>='A' && ch<='Z') ua++; else la++; } else if(ch>='0' && ch<='9') d++; else if(ch==' ') sp++; else spl++; c++; cout.put(ch); } pqr.close(); cout<<"total length "<<c<<endl; cout<<"total alphabets "<<a<<" upper "<<ua<<" lower "<<la<<endl; cout<<"digits "<<d<<" space "<<sp<<" special chars "<<spl<<endl; } int main() { count(); return(0) ; }