Just learning c++. The following function is my attempt to reverse a string (doesn't work and I don't know why). Thank you for spotting my stupidity.
#include <iostream>
using namespace std;
string r(string s)
{
int len = s.length();
for (int i = 0; i < len; i++)
{
char temp = s[i];
s[i] = s[len - i];
s[len - i] = temp;
}
return s;
}
int main()
{
cout << r("ASTRING");
}
It changes first letter of the string to ' ' and outputs STRING
s[len - i]is out of bounds on the first iteration.std::reverse()already does that in a safe and robust way. Don't reinvent the wheel, especially not if it comes out as a square.