Write a program that will read a line of text and output a list of all the lette
ID: 659686 • Letter: W
Question
Write a program that will read a line of text and output a list of all the letters that occur in the text together with the number of times each letter occurs in the line. End the line with a period that serves as a sentinel value. The letters should be listed in the following order: the most frequently occurring letter, the next most frequently occurring letter, and so forth. Case should be ignored ('a' should be treated the same as 'A'). The program will prompt the user to enter the lines of text in the terminal.
Output should should be successful for each of these instances:
#include<iostream>
#include<cctype>
using namespace std;
int main()
{
char arr[50],i=0;
int count[26]={0};
cout<<"Enter text:"<<endl;
gets(arr);
while(arr[i]!='.')
{
arr[i]=tolower(arr[i]);
if(arr[i]>='a' && arr[i]<='z')
count[arr[i]-'a']++;
i++;
}
cout<<"Frequencies:"<<endl;
for(i=0;i<26;i++)
{
if(count[i]!=0)
cout<<(char)(i+'a')<<" "<<count[i]<<endl;
}
system("pause");
return 0;
}
Explanation / Answer
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<map>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct par {
int c;
int f;
}par;
bool pt(par a,par b) {
return (a.f > b.f);
}
int main()
{
cout << "Enter Text: ";
string s;
getline(cin,s);
int i = 0;
map<int,int> m;
map<int,int>::iterator it;
par al[256];
while(s[i] != '.') {
if(s[i] != ' ' && s[i] != '.') {
int l = int(tolower(s[i]));
//cout << l << endl;
m[l-97]++;
}
i++;
}
int k = 0;
for(it = m.begin();it != m.end();it++) {
al[k].f = (*it).second;
al[k].c = (*it).first;
k++;
}
sort(al, al+k,pt);
for(int i = 0;i < k;i++) {
char p = (char)(al[i].c) + 97;
cout << p << " " << al[i].f << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.