0

So I'm working on some review questions for the last chapter in my homework.

My question is, if a user inputs a string sentence, how would I go about counting the number of words? I don't think it was covered in class, or will be covered in class.

I've gotten as far as requesting the sentence and using getline to read the string, but how would I go about counting the individual words other than writing the input to a file, opening the same file, and counting the words that way?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
ccc
  • 1
  • 2

3 Answers3

3

Not a complete answer, because this is homework, but check the functions in <string.h>. You basically want to find the next non-whitespace character in the string, then the next whitespace character, increment your counter, repeat until you reach the end of the string.

Davislor
  • 14,674
  • 2
  • 34
  • 49
0

You can use std::istringstream combined with std::istream_iterator to turn your string into the range of whitespace-separated tokens, like here.

To count the elements in range, just use std::distance.

I guess I won't provide the actual code since it's homework, but feel free to ask further.

Community
  • 1
  • 1
Ap31
  • 3,244
  • 1
  • 18
  • 25
  • Notice how the actual parsing will not happen until the call to `std::distance`. This may be a bit advanced, but it's kinda cool to pack all of your code into couple of library calls. Perhaps it would be a good practice to do it by hand at the same time just to keep track of what's going on though. – Ap31 Sep 11 '16 at 04:06
0

Suppose str is a char * which is the input sentence:

int count = 0;
for(int i = 0; i < strlen(str); i++){
    while(i < strlen(str) && str[i] != ' ')
        i++;
    count++;
}

This is how you can do the counting manually without any special method of class string.h.

Athena
  • 543
  • 10
  • 30
  • There are a couple of drawbacks though: it only considers `' '` to be a delimiter, and that's only one specific kind of whitespace; It counts the number of space characters, and it is very much not the same as the number of words. Besides it's more of a C code than C++, so you might as well stick with C to the end, like this: `int count=1,i=0; while(str[i]) count+=(str[i++]==' ');` – Ap31 Sep 11 '16 at 05:45
  • Any loop that contains `strlen` in its condition is highly suspect. – Sebastian Redl Sep 11 '16 at 09:34