help with string reversing code

closed account (N0M9z8AR)
I need help with this code, I am trying to output yes when the reversed of the string is the same as original and no if it's not, every time I run the code even if the reversed is the same it outputs no.

can someone help, thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>

using namespace std;

int main()
{
    string letter, letter2;

    cin >> letter;

    for(int i=letter.length(); i>=0; i--) {

    letter2=letter[i];

}



if(letter==letter2) {
    cout<<"YES";
}
else  {
    cout<<"NO";
}



return 0;

}
Hello Rufyi,

The best I can think of right now is that you are trying assign a single char to a string which leaves "letter2" blank and that is why your if condition is always false because it is comparing a blank string to one with something in it.

I have not figured out how to fix what you have yet, but you could replace the for loop with:

1
2
3
letter2 = letter;

std::reverse(letter2.begin(), letter2.end());


which works. This requires the header file <algorithm> for std::reverse.

You are also missing the header file <string>.

Hope that helps,

Andy
Your reverse function will not reverse a string. Every time you go through the loop you are assigning a new letter to letter2. You need to be adding a letter on to letter2 (you will need to use a +). An easier way to do it though would be reverse(letter2.begin(), letter2.end());. Assign letter2 = letter; then the reverse function. You may need to #include <algorithm>
Pass the reverse iterators of the original string to the std::string ctor that takes iterators to make the reverse string and check for palindrome:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
    std::string original{};
    std::cout << "Enter original string \n";
    getline(std::cin, original);
    std::cout << ( (original == std::string(original.rbegin(), original.rend())) ?
                  "Yes \n" : "No \n" );
}

ctor #6 from here: http://en.cppreference.com/w/cpp/string/basic_string/basic_string

Topic archived. No new replies allowed.