Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program to count words and numbers in a plain text file. Words and n

ID: 3782625 • Letter: W

Question

Write a C++ program to count words and numbers in a plain text file. Words and numbers can be repeated. You can use any algorithm and data structures that you prefer, as long as the results are correct. It is preferred, but not necessary, that your algorithm is as efficient as possible, both in processing time as well as memory management.

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. For this homework we will not ask you to consider all potential inputs. Notice you are not asked to handle floating point numbers, which require decimal point and scientific notation.

input1.txt

------------------------------------------------------------ The cat is [there] 10 20 3.1416,,1000 another cat -------------------

Explanation / Answer

#include<iostream.h>
#include<fstream.h>

int main()
{
ifstream fin("story.txt"); //opening text file
int digits=1,word=1,i,size; //will not count first word so initial value is 1
char ch;
fin.seekg(0,ios::end); //brings file pointer position to end of file
size=fin.tellg(); //counts number of bytes till current postion for file pointer

fin.seekg(0,ios::beg); //brings position of file pointer to begining of file

while(fin)
{
fin.get(ch);

i=ch;
if(ch==' '||ch=='n')
word++;
if(i>47&&i<58)
digits++;
}

cout<<"Words="<<word<<"nDigits="<<digits<<"n";
fin.close(); //closing file

return 0;

}

output:

$ cat>story.txt

$cat>>story.txt

hello hai 123 example

so output is

words:3

digits:1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote