Bug in function using String and Find func

Sep 11, 2018 at 4:15am
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;
Sep 11, 2018 at 7:25am
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
Sep 11, 2018 at 8:38am
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.
Sep 11, 2018 at 8:54am
Yes I was wrong. The cpp reference states:
If this is greater than the string length, the function never finds matches.
Sep 11, 2018 at 12:58pm
What if getline() fails?
Sep 11, 2018 at 2:40pm
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?
Sep 12, 2018 at 7:01pm
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.
Sep 12, 2018 at 9:42pm
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 Sep 12, 2018 at 9:44pm
Sep 15, 2018 at 4:06pm
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.