7.6. A run-time error¶
Way back in Section 1.4.2 I talked about run-time errors, which are errors that don’t appear until a program has started running.
So far, you probably haven’t seen many run-time errors, because we
haven’t been doing many things that can cause one. Well, now we are. If
you use the []
operator and you provide an index that is negative or
greater than length-1
, you will get a run-time error and a message
something like this:
index out of range: 6, string: banana
Try it in your development environment and see how it looks.
Running the active code below will result in a runtime error. Can you fix
it so that we print out the first letter and last letter of string greeting
instead
of indexing out of range?
int main() { string fruit = "apple"; char letter = fruit[0]; char letter = fruit[9]; cout << fruit << endl; cout << fruit[-4] << endl; cout << fruit[4] << endl; }
Construct a block of code that correctly changes the string to say “cat in the hat” instead of “cat on the mat”, then print it.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.