-4

I need to make a function that identifies the number of words by spaces (Ignoring trailing and leading ones). I'm having trouble with the equation that recognizes a space within the string variable. It doesn't count a space like it should. I should be getting the number "2" with the test case I have.

#include<iostream>
#include<string>
using namespace std;

void numWords(string phrase)
{
    for (int index = 0; index < phrase.length(); index++)

        int words = 0;
            int space = 0;

    if (phrase[index] == ' ')
    {
        words++;
        space++;
    }
}

if (space == 0) //This is for single words with no spaces 
{
    words++;
}
cout << words << endl;
}

int main()
{
    string phrase;
    int words = 0;

    numWords("hello, world");
    //A test case

    return 0;
}
  • "I'm having trouble " you need to be more specific. You get a compile error? You get a runtime error? You get no errors but you get unexpected results? If you get errors post them. If you get unexpected results post them. – bolov Oct 18 '18 at 19:31
  • It might help you to read about [fencepost errors](https://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error). – aschepler Oct 18 '18 at 19:31
  • `int words, space = 0;` Variable `words` is not initialized. – Galik Oct 18 '18 at 19:35
  • "It doesn't count a space like it should." It doesn't even compile ... – Swordfish Oct 18 '18 at 19:37
  • Your indentation was lying to you. I've edited the question so indentation properly reflects your actual scopes. – François Andrieux Oct 18 '18 at 19:37
  • @Galik I initialized them individually like you suggested but I'm getting the default "1" output when the test case has 2 words. – Mercurius72 Oct 18 '18 at 19:39
  • What lines do you think your for loops over? – stark Oct 18 '18 at 20:39

2 Answers2

0

Problems with your code / your approach:

  1. You haven't initialized the number of words.
  2. You count words and spaces the exact same way - but they're not the same.
  3. You haven't properly defined what's a word:

    • Does the empty string contain a word?
    • If a space delimits words, is there an empty word between two consecutive spaces?
    • What about punctuation marks, do they count as parts of words?
    • What about non-printing characters?

So, there's little wonder your output doesn't satisfy your expectations.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
0

check the solution of "dash-tom-bang" in : C++ function to count all the words in a string

a Copy of it

#include <cctype>

int CountWords(const char* str)
{
    if (str == NULL)
    return error_condition;  // let the requirements define this...

    bool inSpaces = true;
    int numWords = 0;

    while (*str != NULL)
    {
        if (std::isspace(*str))
        {
            inSpaces = true;
        }
        else if (inSpaces)
        {
           numWords++;
           inSpaces = false;
        }

        ++str;
    }

    return numWords;
}