WORD COUNT

I have been trying to write a code that counts words and sentences, yet I do not think I have the right logic. I need to write code only using beginner principles like using loops and functions, not vectors.

I have this code, but I need help trying to write this code not using vectors and only using very basic code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <vector>
using namespace std;
 
int word_count ( string sentence )
{
	int length = sentence.length();
	int words = 1;
	
	for (int size = 0; length > size; size++)
	{
		if (sentence[size] == ' ' && sentence[size-1] != ' ')
			words++;
	}

	return words;
}
int main ()
{
	string user_input;
	cout << "Enter your text: \n";
	getline(cin,user_input);

	cout << "There are " << word_count(user_input) << " words.\n";
	return 0;
}

Last edited on
I'd recommend looking one ahead, not one behind. When your program starts, you'll be searching in sentence[-1].

Also, I admire that you tried to separate your code from the rest of your text. Just so you know, we have [code] tags that do this for you AND put in all the fancy formatting.

-Albatross
closed account (Lv0f92yv)
Also, it might be worth considering the case where 'sentence' contains no words (is empty). This might be a rare case depending on the usage of your program, but a simple check beforehand can eliminate this problem:

1
2
3
int words = 0; //start at 0
if ( length > 0 ) //if there is something in the string, it must have a length > 0
   words++; //we have one additional word 
Last edited on
According to your code, you probably are not counting the last word.
There is no space after it.
Although he does include one more word at the start of his loop.

-Albatross
Topic archived. No new replies allowed.