Number of words in a string I wrote this pretty simple program (it's an exercise from a book). It counts the words in a simple string. The book is a very old one (I think it's from 2003) and uses char arrays. Because of this, I don't know if this solution is a proper one or not.

Can you tell me whether it is okay or not? 

#include &lt;iostream&gt;

int main()
{
    int count_words(std::string);

    std::string input_text;
    std::cout&lt;&lt; "Enter a text: ";
    std::getline(std::cin,input_text);

    std::cout &lt;&lt; "Number of words: " &lt;&lt; count_words(input_text) &lt;&lt; std::endl;
    return 0;
}
int count_words(std::string input_text)
{
    int number_of_words = 1;
    for(int i = 0; i &lt; input_text.length();i++)
        if(input_text[i] == ' ')
            number_of_words++;
    return number_of_words;
}
Prefer std::size_t for the word count and count_words()'s return type.  Also prefer std::string::size_type for the loop counter (when using indices is needed).
count_words()'s parameter should be passed by const&amp; since it's not being modified:

std::size_t count_words(std::string const&amp; input_text) {}

count_words() has a problem.  If I press ENTER without typing anything, it gives me 1.  To fix this, return 0 if the string is empty:

if (input_text.empty()) return 0;

In the for-loop, prefer std::isspace for detecting whitespace.
Prefer iterators over indices for std::string:

for (auto iter = input_text.cbegin(); iter != input_text.cend(); ++iter)
{
    if (*iter == isspace)
    {
        number_of_words++;
    }
}


If you have C++11, use this range-based for-loop instead:

for (auto&amp; iter : input_text)
{
    if (iter == isspace)
    {
        number_of_words++;
    }
}

As @r-s mentions, this just counts whitespace.  Here's another solution from this answer:

unsigned int countWordsInString(std::string const&amp; str)
{
    std::stringstream stream(str);
    return std::distance(std::istream_iterator&lt;std::string&gt;(stream), std::istream_iterator&lt;std::string&gt;());
}


I realize this may be difficult to understand.  I'd still recommend holding onto the answer for future reference.  If you want to try it out, include &lt;sstream&gt; and &lt;iterator&gt;.