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?
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++;
}