Reputation: 39
I have tried my best to fix my logic, but I can't detect the error. I can't use [] or any other advance features, as I haven't covered them yet. If you can, please tell me my mistake.Please don't give me negative points because I have tried my hardest, and my error doesn't make sense! Thanks.
This script is supposed to reverse the input string: for example: hi to ih.
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
void ReverseString(string &aString);
int main(){
string info;
cout << "What's your string?" << endl;
getline(cin, info);
cout << info << " compare with: " << endl;
ReverseString(info);
cout << info << endl;
system("pause");
return 0;
}
void ReverseString(string &aString)
{
for(int i = 0; i < aString.length(); i++)
{
int u = aString.length() - 1 - i;
string temp = "";
temp += aString.at(aString.length() - 1 - i);
if(u == 0 )/* when aString.length() - 1 - i == 0, the last char will have been processed*/
{
aString = temp; /*store temp into aString; when its value changes, it is passed into info's value*/
}
}
}
Upvotes: 1
Views: 186
Reputation: 2479
You should keep it simple, what you want is to look at the last character of the old string and put it at the end of the new string. So instead of looping from 0 to end, you loop from end to 0. But you should declare your new string before the loop because if you do it inside the loop you will always throw the contents away after each iteration.
string newString;
for(int i = aString.length() - 1; i > 0; i--) {
newString.append(aString.at(i));
}
Upvotes: 1
Reputation: 154017
The classical idiom involves swapping, and maintaining two indices:
void
ReverseString( std::string& target )
{
int bottom = 0;
int top = target.size();
while ( top > bottom ) {
-- top;
char tmp = target[top];
target[top] = target[bottom];
target[bottom] = tmp;
++ bottom;
}
}
(In practice, I'd use std::swap
in the loop, but I imagine
that that's also banned.)
This does the job in place, and avoids the extra intermediate string.
Upvotes: 1
Reputation: 620
Your problem is that every time you run through your for loop in ReverseString()
, you're re-initializing your temp
variable, deleting everything you've already saved in the string. Your program works as expected if I do this to the ReverseString function:
void ReverseString(string &aString)
string temp = "";
for(int i = 0; i < aString.length(); i++)
{
int u = aString.length() - 1 - i;
temp += aString.at(aString.length() - 1 - i);
if(u == 0 )/* when aString.length() - 1 - i == 0, the last char will have been processed*/
{
aString = temp; /*store temp into aString; when its value changes, it is passed into info's value*/
}
Upvotes: 2