I'm learning C++ and looping through "Hello World" with text.at(i). The loop starts at zero and runs while i <= text.length(). It prints the characters, then terminates with std::out_of_range saying index 11 is greater than or equal to size 11. What's going wrong?
Why does my C++ string loop terminate after printing everything?
Answers
The loop runs one time too many. The string has 11 characters, but their indices are 0 through 10. Your condition also allows i to be 11, so text.at(11) throws.
Change the condition to i < text.length(). That stops the loop before the invalid access, including when the string is empty.
Reply to this answer
The error message is pointing right at the failed check: at() throws std::out_of_range when the index is greater than or equal to the string's size. All the characters print first because those accesses are valid. The next access throws, and the uncaught exception causes termination.
There is a terminating null character associated with the string, but at() doesn't let you access it at position size(). Fix the loop boundary rather than trying to print it.
Reply to this answer
If you just want to visit each character, a range-based loop avoids the index altogether: for (char c : text) can print c on each iteration. That also works for an empty string without any special case.
Reply to this answer
Separate from the crash, textEngine currently takes the string by value, so it makes a copy. If it only reads the text, consider taking a const std::string& instead. The return value also isn't needed if the function's only job is printing.
Reply to this answer
Add your answer
Answers are reviewed before publication.
counterclockwise-kiosk:
That makes sense. I was counting the length as if it were the last index.