Help with string find() loop?

I am asked to use the find function for a string to find the number of blank spaces in string input. However, this program does not give the correct answer. Can anyone tell me what is wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
#include <string>
using namespace std;

void main()
{
	string x;
	int counter = 0;
	cout << "Enter a string of text: " << endl;
	getline(cin, x);
	int length = x.length();
	for (int i = 0; i < length; i++)
	{
		int p = x.find(" ", i);
		if (p != -1)
			counter++;
	}
	cout << counter << endl;
	system("pause");
}
You problem is that using i as an offset in find(...) you will find the same space multiple times. E.g. for "abc d" you will find the space 4 times. I.e. you will find it as long as i <= the position of the space. To avoid that use the last found offset + 1 to find the real next space.

One approach could be this:
1
2
3
4
5
	for (size_t i = x.find(' '); i != string::npos; i = x.find(' ', i + 1))
	{

			counter++;
	}
Topic archived. No new replies allowed.