0

I have a question about comparing strings in C++. My code below is supposed to check if a word is a palindrome (spelled the same way forward and backwards). The problem is that my if statement (s1 == s2) never evaluates to true. I have the feeling that in memory these two strings are different, but I don't have any concrete proof. Any advice? Thanks!

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s1, s2;
    cin >> s1;

    for(int i = 0; i <= s1.size(); i++){
        s2.push_back(s1[(s1.size() - i)]);
    }
    cout << s1 <<endl;
    cout << s2 <<endl;


    if(s1 == s2){
        cout << "Correct" <<endl;
    }
    else {
        cout << "Incorrect" <<endl;
    }
    return 0;
}
1
  • My best advice is to display the values of the two strings and check for yourself. Failing that, run your program under a debugger. Step through each line and decide if it is behaving as intended. Commented Feb 17, 2012 at 21:18

7 Answers 7

4

This is going out of bounds for the strings

for(int i = 0; i <= s1.size(); i++){
    s2.push_back(s1[(s1.size() - i)]);
}

A string only has chars in the range 0..size()-1. You are both counting and indexing one position too far.

Sign up to request clarification or add additional context in comments.

Comments

3

But you should better use the following instead of your loop:

s2.assign(s1.rbegin(), s2.rend());

Comments

1

Your problem is not in the string comparison. Have a look at how you're building the reversed string.

Comments

0

Index is out of range in your case. Here is the correct code (i is initialized with 1, not 0):

for(int i = 1; i <= s1.size(); i++){
        s2.push_back(s1[(s1.size() - i)]);
    }

Comments

0

You probably meant s1.size() - i - 1.

Comments

0

Because i starts at 0, you will access s1[s1.size()-0], which will return the null character. Note that the solutions suggesting you use s1.size() - i - 1 are wrong, as you are iterating up to and including s1.size(), which means you would at some point access s1[-1]. That's much worse than accessing s1[s1.size()], as the behaviour is undefined. Start iterating at 1, and then you can leave the rest of the code unchanged (but please do indent it!).

As others have mentioned, defining s2 as std::string s2(s1.rbegin(), s1.rend()); is even clearer.

Comments

-4

ofcourse. you're comparing the pointers of the two vars. you should use strcmp function

fix: you need to use: string::compare

good luck

2 Comments

sorry, you should use instead cplusplus.com/reference/string/string/compare
No, the string operator== is using string::compare, so they are equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.