Write a program that reads the text and displays the number of one-letter, two-letter, etc. words. Words are divided by the characters: '', ',', ',' and '.'. Input: text on one line, no more than 1000 characters. Output: n rows of integers indicating the numbers of words with the corresponding lengths, n is the length of the longest word in the text.
I think I'm having a slight idea of how to count all of the words but strlen is yet unfamiliar to me and don't know how to proceed. Any help will be appreciated, thanks.
#include <iostream>
using namespace std;
int main()
{
char a[1000];
short count[1000];
int wc = 0;
int max = 0;
for (int i = 0; i < 1000; i++)
count[i] = 0;
for (int i = 0; i < 1000; i++)
{
cin >> a[i];
if ('\n')
break;
}
for (int i = 0; i < 1000; i++)
{
if (a[i] != ' ' && a[i] != ',' && a[i] != ';' && a[i] != '.')
wc++;
else
{
if (wc != 0)
{
count[wc]++;
if (wc > max)
max = wc;
}
wc = 0;
}
}
for (int i = 0; i < max; i++)
cout << count[i] << endl;
return 0;
}
Could someone fix it for me, please?
Under the circumstances, you don't really even need to read strings at all. You don't care about the content of each word, only its length. As such, you can just read and process one character at a time. When you read a non-delimiter character, increment the current word size. When you read a delimiter character, check if the current word size is non-zero. If it is, increment the count for that size of word. Also check whether the current count is larger than any count you've recorded before. If so, set the largest count to the current count.
Start with an array of 1000 shorts, all set to 0 as your counts for the different word sizes.
After processing all your input, you have a record of the longest word, so print out the counts from the array for all items from one through that maximum.