Can you spot the error?

I've been refreshing my mind on the various string functions and I've come across this code example on the internet that says that there's a bug in this code. I've been trying to figure this out for a good thirty minutes by running this code and trying various possibilities. What this little code sample does is detect if there is a space after a word. What do you think this subtle error might be?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string text;
getline (cin, text);
 
string::size_type position = text.find (' ');
if (position != string::npos)
{
    if  (text.find (' ', position+1) != string::npos)
    {
        cout << "Contains at least two spaces!" << endl;
    }
    else
    {
        cout << "Contains less than two spaces!" << endl;
    }
}
else
{
    cout << "Contains no spaces!" << endl;
}
If the string ends with space and this space is the only one, then position+1 on line 7 would refer outside string.

EDIT: ...and it is not a bug as .find behaves correctly in this case.
Last edited on
Topic archived. No new replies allowed.