Hello everyone, I unfortunately had to take a little break from learning programming so I have forgotten a few things and a little rusty, so I apologize if the answer is blatantly obvious.
I had to write a small program that takes a string that the user enters and reverses it. After spending awhile trying I got it working with this...
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string s = "";
int cnt = 0;
cout << "Please enter a string: ";
getline(cin, s);
string r = s;
for (int i = s.length(); i > 0; i--)
{
r[cnt] = s[i];
cnt++;
}
cout << "Reversed string = " << r << endl;
cout << endl;
system("Pause");
return 0;
}
It reverses most of the string but doesn't show the first character of the original string. For instance Hello comes out as olle. I've also tried some slight variations such as..
1 2
for (int i = s.length() + 1; i > 0; i--)
for (int i = s.length(); i >= 0; i--)
I am wondering why this code won't work correctly it seems like it should to me.
std::string Reverse(std::string str="")
{
if(str.length() > 1)//we don't need to reverse if the string is empty or 1
//it has to have at least 2 characters to make sense to reverse it
{
std::string newStr = "";
for(int i=str.length() -1; i>=0; i--)
newStr += str.at(i);
//at() is similar to str[i], but this last one doesn't throw an exception
return newStr;
}
return str;//returns the string if its length <= 1
}
I can't believe I forgot about starting at 0 and the '\0' that would be at the very end of the string. Well, I didn't really forget since I started at 0 with..
1 2 3 4 5 6
int cnt = 0;
for (int i = s.length(); i > 0; i--)
{
r[cnt] = s[i];
cnt++;
}