I need to write a program that will take in a sentence and then outputs the # of words in the sentence, as well as the each letter with it's occurrence in alphabetical order.

Example:
Hello World.

Would output:
2 words
1 d
1 e
1 h
3 l
2 o
1 w

This should be done using strings and vectors. I'm a bit miffed on how to accomplish this. Any help / point in the right direction would be great.

Was your other thread no good enough?

keep counter on each character entered

I would use array for store the number of alphabet that we found in the string. Start to count from the first character of the string till the last character of the string. You should also count the space because space can determine how many words in your string.

Member Avatar for iamthwee

I'd begin by taking it one step at a time. For example just try to get it so that the program can accept user input, then count the number of words and then display them.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  string line;

  cout << "Enter a sentence to finish with a '.':\n\n";

  getline ( cin, line, '.' );

  istringstream in ( line );
  vector<string> words;
  string word;

  while ( in >> word )
  {
    words.push_back ( word );
  }

  cout << "You typed " << words.size() << " words\n";

  cout << "The words are:\n";
  for ( int i = 0; i < words.size(); i++ )
  {
    cout << words[i] << endl;
  }
  cin.get();
  return 0;
}

I'd begin by taking it one step at a time. For example just try to get it so that the program can accept user input, then count the number of words and then display them.

I would do this:

#include <iostream>

int main()
{
   int letter_count[26];
   int words_count = 1;
   char* string = "I need to sleep now.";

   // Initialization
   for(int i=0; i<26; letter_count[i++]=0);

   // Counting the number of letters and words
   for(int i = 0; string[i] != '\0'; i++) {
      if(string[i] > 64 && string[i] < 91)
         letter_count[string[i]-65]++;
      else if (string[i] > 96 && string[i] < 123)
         letter_count[string[i]-97]++;
      else if (string[i] == ' ')
         words_count++;
      else if (string[i] == '.')
         break;
   }

   // Show the result
   std::cout << "There are " << words_count << " words in this sentense" << std::endl;
   for(int i=0; i < 26; i++)
      if (letter_count[i] != 0)
         std::cout << letter_count[i] << " "<< char(i+97) << std::endl;
}

I would let the OP post his code before writing it for him...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.