|
| ljrobison (53) | |||
| Hello all, I have an assignment which reads: Using the at() function, write a C++ program that reads in a string by using getline() and then displays the string in reverse order. For some reason when I run my code it says theres a runtime error and crashes.
Does anyone know why this is happening? | |||
| jsmith (3099) | |
| zero-based indices on strings. a string of length N (N>0) has valid indices 0 .. N-1, inclusive. | |
| ljrobison (53) | |
| Sorry, can you clarify what that means? | |
| firedraco (2048) | |
| He means a string has a 0 based index, which means it starts at 0 and goes to (size-1). In your code you are accessing element (size), which is not in the valid range. | |
| ljrobison (53) | |||
Ok I changed it to:
And now it runs, but it just reprints the string and doesnt reverse it. Thats why I used the for loop I had before so it would get the character in the last index of the string and print it on the console and then count down. So what should I do now? | |||
| firedraco (2048) | |
| Your original for loop was more correct. You want to go from the end of the string to the beginning. Hint: What is the index of the "end" (last element)? What is the index of the "beginning" (first element)? | |
| ljrobison (53) | |||
Ok I got it =) Thank you so much.
See any problems? I only tested it a few times. But it seems to be working. | |||
| firedraco (2048) | |||
That should work. I would have done it this way, but your way works as well:
| |||
Last edited on | |||
| jsmith (3099) | |||
| I know that you have to use the at() function, but in the interest of "higher education", you should consider independently researching iterators. Iterators make things so much easier by simply avoiding the "off-by-one" problems associated with using integer indices. Strings have iterators similar to that of containers. Using a (const) reverse_iterator, you could write the loop as:
| |||
Registered users can post in this forum.
