Search code examples
c++strcmp

strcmp returning 0 always on comparing string with reverse


I am making the user input a string and then comparing the reverse of it , but it is always giving 0 as result, why?

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
    char *str=new char[100];
    cout<<"enter a string";
    cin.getline(str,100);
    int len=strlen(str);
    char *rev=strrev(str);
    int diff=strcmp(str,rev);
    cout<<diff;
    return 0;
}

Solution

  • strrev reverses a string in place. So it actually modifies your character array that str points to. If you were to do printf("%s", str); you would see that it has been reversed.

    You should make a copy of the string and reverse that:

    int main() {
        char *str = new char[100];
        char *rev = new char[100]; // You need memory for the reversed string
    
        cout << "enter a string";
        cin.getline(str, 100);
    
        strcpy(rev, str); // Make a copy of `str` called `rev`
        strrev(rev);      // Reverse it.
    
        int diff = strcmp(str, rev);
    
        cout << diff;
        return 0;
    }