In: Computer Science
Please, write code in c++. Using iostream library.
Most modern text editors are able to give some statistics about
the text they are editing. One nice statistic is the average word
length in the text. A word is a maximal continuous sequence of
letters ('a'-'z', 'A'-'Z'). Words can be separated by spaces,
digits, and punctuation marks. The average word length is the sum
of all the words' lengths divided by the total number of
words.
For example, in the text "This is div2 easy problem". There are 5 words: "This"is"div"easy" and "problem". The sum of the word lengths is 4+2+3+4+7 = 20, so the average word length is 20/5 = 4.
Given a text, return the average word length in it. If there are no words in the text, return 0.0.
Input
The first line will contain the text of length between 0 and 50
characters inclusive. Text will contain only letters ('a'-'z',
'A'-'Z'), digits ('0'-'9'), spaces, and the following punctuation
marks: ',', '.', '?', '!', '-'. The end of text will be marked with
symbol '#' (see examples for clarification).
Output
Output should contain one number - the average length. The returned
value must be accurate to within a relative or absolute value of
10-9.
example:
input:
This is div2 easy problem.#
output:
4.0
//code:
#include<iostream>
using namespace std;
//whether a character is digit or not
bool isDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
int main()
{
char str[100];
int i,word_count=1,len_of_word=0;
cout<<"Enter a string:";
cin.get(str, 100);
for(i=0;str[i]!='\0';++i)
{
if(str[i]==' '){
//gives word_count
word_count++;
}
else if((!isDigit(str[i])) && (str[i]!='.' && str[i]!='#'&& str[i]!=','&& str[i]!='?'&& str[i]!='!')){
//length of each character in a word
len_of_word++;
}
}
double avg=len_of_word/word_count;
printf("%.1f", avg);
return 0;
}
//screenshot of the code
//output:
NOTE: