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

Write a program that will read in a line of text and output the number of words

ID: 3669712 • Letter: W

Question

Write a program that will read in a line of text and output the number of
words in the line and the number of occurrences of each letter.


Define a word to be any string of letters that is delimited at each end
by either whitespace, a period, a comma, or the beginning or end of the line.


You can assume that the input consists entirely of letters, whitespace, commas,
and periods.

When outputting the number of letters that occur in a line, be sure to count upper-case and lowercase versions of a letter as the same letter.


Output the letters in alphabetical order and list only those letters that do occur in the input line.

For example, the input line

I say Hi.

should produce output similar to the following:

3 words
1 a
1 h
2 i
1 s
1 y

feel free to use any style you prefer (OOP or procedural)

Explanation / Answer

#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;

int CountWords(string strString);
char add_letter( char letter, int counters[] );

int main(){
std::string input;
int counters[26] = { 0 };

//request String
cout << "Please enter a sentence. ";
getline(cin, input);

//Display Word Count
cout << " " << CountWords(input) << " Words" << endl;

char *sentence=new char[input.size()+1];
sentence[input.size()]=0;
std::memcpy(sentence,input.c_str(),input.size());

//Count Letters
while ( add_letter(*sentence++, counters) );

//Display Letter Results
for (int i = 0; i < 26; ++i) {
if ( counters[i] ) {
cout << counters[i] << ": " << char(i + 'a') << ' ';
}
}

cout << " Press enter to exit. ";
cin.get();
return 0;
}

int CountWords(string strString){
int nSpaces = 0;
unsigned int i = 0;

while(isspace(strString.at(i)))
i++;

for(; i < strString.length(); i++){
if(isspace(strString.at(i))){
nSpaces++;

while(isspace(strString.at(i++))){
if(strString.at(i) == ''){
nSpaces--;
}
}
}
}

return nSpaces + 1;
}

char add_letter( char letter, int counters[] ) {
char lower_case_letter = tolower(letter);
if ( lower_case_letter >= 'a' && lower_case_letter <= 'z' ) {
++counters[ lower_case_letter - 'a' ];
}
return letter;
}

Out Put:

Please enter a sentence.

i am Software engineer

4 Words

2: a

4: e

1: f

1: g

2: i

1: m

2: n

1: o

2: r

1: s

1: t

1: w

Press enter to exit.

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