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 b 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 and lowercase versions of a letters as the same letter. Output the letters I alphabetical order and list only those letters that do occur in the input line.

Respuesta :

Answer:

Here is the C++ program:

#include<iostream>  //to use input output functions

#include <algorithm>  //to use tolower() function

using namespace std;  //to identify objects like cin cout

int main() {  //start of main function

 string text;  // to hold text input

 cout<<"Enter a line of text: ";  // prompts user to enter a string

 getline(cin,text);  // reads the input string (text) from user

transform(text.begin(), text.end(), text.begin(), ::tolower);  //converts the text into lower case

 int letter[26] = {0}; //to hold the letters

 int i;  // used as a loop variable

 int words=0;  // to hold the count of words

 for(i = 0; i< text.size();i++){  // iterates through the text

 if(isalpha(text[i])&&(text[i+1]=='.'||text[i+1]==','||text[i+1]==' '))  //checks if the character at i-th index of text is a letter, and checks if i+1 index position of text is a period, comma or a space

 words++;  // adds 1 to the count of words

 if(isalpha(text[i]))  // if the character at the i-th index of text is a letter

 letter[text[i]-'a']++;  }  // counts the occurrences of each letter

 char j = text[text.size()-1];  // sets j to the last character of text

 if(j != '.' && j!= ' '&& j!=',' &&j!= '\0')  //if the last character is not a period or empty space  or comma or end of lone

 words++;  //add 1 to the count of words

 cout<<"Number of words: "<<words<<endl;  //display the number of words in the text

 for(i=0; i<26; i++)  {  //iterates 25 times

   if(letter[i]>0)  //if letter at index i is greater than 0

   cout<<(char)('a'+i)<<" : "<<letter[i]<<endl;  }} //displays each letters and its number of occurrences in the text

 

Explanation:

The program is explained in the attached document with an example.

Ver imagen mahamnasir
Ver imagen mahamnasir