Write a C++ program to count words and numbers in a plain text file. Words and n
ID: 3783773 • Letter: W
Question
Write a C++ program to count words and numbers in a plain text file. Words and numbers can be repeated.
The input is one text file, with words and integers, separated by any other symbols including spaces, commas, period, parentheses and carriage returns. Keep in mind there can be be multiple separators together (e.g. many spaces, many commas together). The input is simple. You can assume a word is a string of letters (upper and lower case) and a number a string of digits (an integer without sign). Words and numbers will be separated by at least one non-letter or one non-digit symbol. Length: You can assume one word will be at most 30 characters long and a number will have at most 10 digits. Repeated strings: words and numbers can be repeated. However, you are not asked count distinct words or compute frequency per word, which require algorithms and data structures to be covered in the course. Therefore, you just simply need to count word or numver occurrences.
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string fileName;
//CountWordsAndNumbersInput.txt
cout<<"Enter the name of the file: ";
cin>>fileName;
ifstream fin;
fin.open(fileName);
if(!fin.is_open())
{
cout<<"Unable to open the input file..."<<endl;
return 0;
}
char ch;
int wordCount = 0;
int numberCount = 0;
while(!fin.eof())
{
fin>>noskipws>>ch;
//cout<<ch<<" ";
if(isalnum(ch))
{
if(isalpha(ch))
{
wordCount++;
while(isalpha(ch))
fin>>noskipws>>ch;
}
else
{
numberCount++;
while(isdigit(ch))
fin>>noskipws>>ch;
}
}
}
cout<<"The words count in the file is: "<<wordCount<<endl;
cout<<"The numbers count in the file is: "<<numberCount<<endl;
}
If you need any refinements, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.