Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
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.
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?
Q-2: Click on each spot that would cause a runtime error.Remember, an index that is negative or greater than the length of the string - 1 will give a run-time error.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.
int main() {
string sentence = "cat on the mat";
sentence[4] = "i";
sentence[5] = "i"; #distractor
sentence[3] = "i"; #distractor
sentence[11] = "h";
sentence [12] = "h"; #distractor
sentence[11] = "h" #distractor
cout << sentence << endl;
}
You have attempted
of
activities on this page