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.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
usingnamespace std;
int main ()
{
string str;
int i;
getline(cin,str);
int size = str.length();
for (i= 0; i <= (size - 1); i++)
{
cout << str.at(i);
}
return 0;
}
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?
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:
1 2
for( std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i )
std::cout << *i;