Bug in function using String and Find func

I found this fragment of C++ code in a website. Apparently there is a bug in this code. I test all conditions but they work as expected. Can anyone help me with this bug.

1
2
3
4
5
6
7
8
9
    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;
The bug is on line 6 if(text.find(' ', position + 1) != string::npos)
If you enter only 1 space you invoke undefined behavior because position + 1 is out of range
Sadly it works on VS 2017
The code does not invoke undefined behaviour as far as I can see. Passing a position that is out of bounds to std::string::find is guaranteed to return npos.
Yes I was wrong. The cpp reference states:
If this is greater than the string length, the function never finds matches.
What if getline() fails?
dhayden wrote:
What if getline() fails?
text would remain unchanged, i.e. empty. The answer would be "Contains no spaces!"

Apparently there is a bug in this code.
A bug is something that behaves different from expectation. When it does what you expect, how could there possibly be a bug?
text would remain unchanged, i.e. empty. The answer would be "Contains no spaces!"

But that's the wrong answer, at least in my opinion. "Failure to read" is quite different from "read a string with no spaces." The situation calls for a different output message.
It's just a code snippet. Exceptions could have been enabled earlier in the code using cin.exceptions(istream::failbit | istream::badbit); so that If getline fails the exception could be caught elsewhere to output an appropriate error message.
Last edited on
The original question was to find the bug in the code. I think the answer is that it doesn't check for errors from getline().
Topic archived. No new replies allowed.