Hello world help

closed account (z8qG1hU5)
The hello world
Last edited on
That's kind of a funny way of looking at it.

Consider it like this: a word is any continuous sequence of just letters. So every time you meet a not-a-letter following a letter, you can count that as a word.

    1 fish, 2 fish, red fish, blue fish.

Here I have underlined the instances where you have a letter followed by a not-a-letter.
There are four of them, so there are four words.

As you loop through the string, all you need is to keep track of the last character's state (was it a letter or not). If (last char was a letter but current letter is not) then you can increment the number of words found.

There is only one possible complication: the input string may end with a letter. You need to count that word too.

So if SENTINEL and uppercase letters are not part of your assignment you should not be messing with them.

Also, read your input, then parse.

1
2
3
#include <cctype>
#include <iostream>
#include <string> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
  int num_words = 0;

  string s;
  while (getline( cin, s ))
  {
    bool last_was_a_letter = false;
    for (char c : s)
    {
      if (!isalpha( c ))
      {
        Current is not a letter. What should I check to see if I should increment num_words?
      }
      last_was_a_letter = (is current a letter?)
    }
    Now we have gone through the entire string. What should I check to see if there was a final word that hasn't been counted yet? 

Once you get that going, you can add stuff like
- counting the size of the longest word
- counting digits
- counting uppercase letters

Hope this helps.
Topic archived. No new replies allowed.