There is a program written that reads from standard input and keeps track of wor
ID: 3624595 • Letter: T
Question
There is a program written that reads from standard input and keeps track of words that are read. Here a "word" is any contiguous sequence of alphanumeric characters. The program displays a list of words found along with their frequency of occurrence. The words are output in alphabetical order with 3 words per line. The program also tells the user how many words ( both total and distinct) were read. Sample output from words.5 would be like that below:Word Count | Word Count | Word Count |
| | |
All 1 | As 1 | Dick 1 |
Dick, 1 | Did 1 | Jane 1 |
Jane, 1 | Spot 1 | Spot's 1 |
Spot? 1 | a 5 | account 1 |
after. 1 | ago, 1 | altered 1 |
and 1 | away 1 | brokerage 1 |
but 1 | computer 1 | end. 1 |
engineer 1 | ever 2 | executive 1 |
expect, 1 | few 1 | firm. 1 |
for 2 | happened 1 | happily 1 |
happy 1 | he 1 | his 1 |
is 2 | large 1 | lived 1 |
major 1 | might 1 | never 1 |
of 1 | passed 1 | personality. 1 |
pleasant 1 | senior 1 | success 1 |
the 1 | they 1 | to 2 |
top 1 | vendor. 1 | was 1 |
what 1 | wonder 1 | years 1 |
you 2 |
Total Word Count : 64
Distinct Word Count : 55
I have word.5 file
Explanation / Answer
please rate -thanks
you say standard input, which is the keyboard, then you say you have a file. so I used file input
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void countit(string,int[],string[],int&);
int main()
{int count[20],i,n=0,oldpos=0,counter=0,tt;
string s,words[20],word,t;
string::size_type pos;
ifstream in;
in.open("words.5"); //open file
if(in.fail()) //is it ok?
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
for(i=0;i<20;i++)
count[i]=0;
getline(in,s);
while(in)
{oldpos=0;
pos=s.find(' ',oldpos);
while (pos!=s.npos)
{word=s.substr(oldpos,pos-oldpos);
countit(word,count,words,n);
counter++;
oldpos=pos+1;
pos=s.find(' ',pos+1);
}
word=s.substr(oldpos,pos-oldpos);
countit(word,count,words,n);
counter++;
getline(in,s);
}
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if(words[i].compare(words[j])>0)
{t=words[i];
tt=count[i];
words[i]=words[j];
count[i]=count[j];
words[j]=t;
count[j]=tt;
}
for(i=0;i<n;i++)
{cout <<setw(10)<<left<< words[i] << " " << count[i] << " |";
if((i+1)%3==0)
cout<<endl;
}
cout<<" Total word count: "<<counter<<endl;
cout<<"Distinct word count: "<<n<<endl;
system("pause");
return 0;
}
void countit(string word,int count[],string words[],int &n)
{int i;
for(i=0;i<n;i++)
if(word==words[i])
{count[i]++;
return;
}
words[n]=word;
count[n]=1;
n++;
return;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.