140k views
0 votes
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.

User Geretd
by
4.3k points

1 Answer

6 votes

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++)text[i+1]==',' // 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

Step-by-step explanation:

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

Write a program that will read in a line of text and output the number of words in-example-1
User Tim Wachter
by
5.0k points