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.
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.