1

I am writing a function int count_words(string str) that returns a count of all of the words in the string.

The issue is that regardless of the input, the result is 1. Can anyone help?

#include <iostream>
#include <string>

using namespace std;

int count_words(string str)
{
    int i,j;
    j = 1;
    int l = str.length();
    for(i = 0; i < l; i++)
    {
        string c = str.substr(i,1);
        if(c == " ")
        {
            j++;
        }
    }
    cout << "The total word in the string: " << j << endl;
    return j;
}


int main()
{
    string str;
    cout << "Please enter a string: ";
    cin >> str;
    int result = count_words(str);
    return 0;
}
Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373
Xiang Wang
  • 69
  • 1
  • 2
    There's nothing wrong with a question which arrises from a fundamental *conceptual* mistake, especially when all the necessary information to recognize the problem has been included. – Chris Stratton Oct 16 '14 at 20:14

3 Answers3

5

You should use cin.getline if your string contains spaces, as using the >> operator with cin only reads up to the next whitespace

Yann
  • 978
  • 2
  • 12
  • 31
3

See std::cin input with spaces?

Consider iterating over the string:

auto cstyle= str.c_str();
for (int i = 0; i < str.length(); ++i)
{
  if (cstyle[i]==' ')//assumes words are delimited by a single space
  {
    j++;
  }
}
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Mikhail
  • 7,749
  • 11
  • 62
  • 136
-2

You should use: cin.getline, for example:

int main()
{
    cout << "Please enter a string: ";
    unsigned size=10;
    char*chr=new char[size];
    cin.getline(chr,size);
    string str(chr);
    //cin >> str;
    int result = count_words(str);
    return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
ncomputers
  • 3,680
  • 1
  • 15
  • 16
  • 5
    I suspect the downvote might be related to the fact that unlike the others who proposed this solution, you haven't given any explanation of why your method will work when the poster's attempt failed - there's little to be *learned* from your answer. – Chris Stratton Oct 16 '14 at 18:41
  • @ChrisStratton Yes, it can be. – ncomputers Oct 16 '14 at 18:55