Look at your code:
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i - 1] == ' ') {
You start the loop with
i
set to zero. The first thing you do is try to access the
i - 1
element of the array which is index
-1
.
Since C++ arrays are always zero based, there can never be a negative index, and you get an error.
To be honest, 30 seconds with the debugger would have shown you exactly what you were doing wrong, and saved you some time in trying to find out! The debugger is your best friend with any development, so it's well worth spending a little time getting familiar with at least the basics - Google can help you find out how to use it for your specific IDE.
Think about exactly what you are trying to do, and perhaps read this:
How to Write Code to Solve a Problem, A Beginner's Guide[
^] before you go any further.