This code works correctly. However I've been trying to get it to count and output the NUMBER of 3 letter words, 4 letter words etc. I'm not sure how to do this. I was messing around with the count but nothing I try works. Any advice is appreciated! Thanks in advance :)
If you don't want to use maps then you could use a normal int array to keep a tally, provided you set it to a decent size and have a check for word lengths exceeding this size. Alternatively, you could use a vector<int>, resized when necessary.
Use of word.size() will give you the length of each string separated by whitespace. If you want to remove punctuation like apostrophes, full stops, commas etc. then you would have to write a function taking a string as argument and scan its individual characters to check that they are alphabetic - use isalpha() from the header <cctype> - see the reference section of this website. You could also use the STL algorithm count_if should you not want to write your own loops.
#include <iostream>
#include <sstream>
#include <cctype>
#include <string>
usingnamespace std;
int wordLength( string word )
{
int length = 0;
for ( char c : word ) if ( isalpha( c ) ) length++;
return length;
}
int main()
{
constint MAXLENGTH = 10; // Probably should set this bigger
int freq[1+MAXLENGTH] = { 0 };
int overlength = 0;
string word;
stringstream in( "This isn't easy. Three, two, one, go!!!" );
while ( in >> word )
{
int length = wordLength( word );
if ( length <= MAXLENGTH ) freq[length]++;
else overlength++;
}
for ( int i = 1; i <= MAXLENGTH; i++ ) cout << i << ": " << freq[i] << '\n';
cout << "There are " << overlength << " words of more than " << MAXLENGTH << " characters";
}
Here's an automatically-resizing one with a vector<int> to tally the frequencies and count_if to remove non-letters from "words".
#include <iostream>
#include <string>
#include <cstring> // for strtok & strlen
int main()
{
std::string str = "This is a sentence, made up of individual words. A big sentence.";
std::cout << str << "\n\n";
// create a C-string from the std::string.
// parsing out individual words modifies the string.
char *cstr = newchar[str.length() + 1];
std::strcpy(cstr, str.c_str());
// define a pattern for word delimiters
constchar pattern[ ] = " ,.";
// get the words
char* token = std::strtok(cstr, pattern);
while (token != NULL)
{
std::cout << std::strlen(token) << '\t' << token << '\n';
// add code to count each sized word
// get the next word
token = std::strtok(NULL, pattern);
}
// clean up, it pays to be neat
delete[] cstr;
}
This is a sentence, made up of individual words. A big sentence.
4 This
2 is
1 a
8 sentence
4 made
2 up
2 of
10 individual
5 words
1 A
3 big
8 sentence
Now you just have to figure out how you are going to keep track of each sized word.