8.6k views
5 votes
Write a function that reads a text file, which has been opened in main program, and RETURNS the number of alphabetic characters (isalpha), digits (isdigit), punctuation characters (ispunct), and whitespace characters (isspace) in the file.

Here isalpha, isdigit, inpunct and isspace are C++ standard library functions, which are included in header file. More details about these functions are provided in Chapter 10.
Demonstrate the function in a complete program.
Hint
Use get function to read data from the file. For example, if fsIn is an opened input stream, then the following statement reads a character to the variable aChar from the opened file:
fsIn.get(aChar);
To read all data from a file, use while loop as follows:
while (fsIn.get(aChar)) // this is similar to while (fsin >> aChar)
{
……
}

User Rbaskam
by
4.6k points

1 Answer

3 votes

Answer:

See Explaination

Step-by-step explanation:

Code below

#include<fstream>

#include<conio.h>

#include<iostream> //libraries required

using namespace std;

int main(){

ifstream fin("input.txt"); //reading the file from the computer

char character;

int alphabets=0;

int spaces=0,digits=0,pucntuations=0; //initializing the variables

while(fin){ //looping all the characters in the file

fin.get(character); //getting the character one at a time

if(isalpha(character)) // if the character is alphaber we increment the alphabet variable

alphabets++;

else if(character==' ') // if space

spaces++;

else if(isdigit(character)) // if digit

digits++;

else if(ispunct(character)) // if punctuation

pucntuations++;

}

cout<<"Number of Digits:"<<digits<<endl; //priting out the results

cout<<"Number of Spaces:"<<spaces<<endl;

cout<<"Number of Alphabets:"<<alphabets<<endl;

cout<<"Number of Pucntuations : "<<pucntuations<<endl;

return 0;

}

User Spir
by
4.1k points