-1

I'm facing an error while assigning the reverse of a string to another string.

[Error] incompatible types in assignment of 'char*' to char[20]

This is my code

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str[20],str2[20];
    int length;
    cout<<"Enter the string\n";
    cin>>str;
    length=strlen(str);
    str2=strrev(str);
    if(str==str2)
    {
        cout<<"Palindrome"; 
    }
    else{
        cout<<"Not a palindrome";
    }
    return 1;
}

Any explanation on what i've done wrong would be really helpful. Cheers

  • 1
    `if(str==str2)` this would work if you used a std::string instead of a c string. Do you have to use `char*` in this or can you use the proper `c++` string? – drescherjm Jul 04 '21 at 20:10
  • see here: https://stackoverflow.com/questions/4951796/how-to-reverse-an-stdstring – 463035818_is_not_an_ai Jul 04 '21 at 20:18
  • 2
    `std::string str;`...`if (str == std::string(str.rbegin(), str.rend()) { palindrome } else { not palindrome }` – PaulMcKenzie Jul 04 '21 at 20:20
  • 7
    The use of `string.h` as opposed to `string` (or even `cstring` would be marginally better) indicates a poor tutorial. Throw out whatever tutorial you're using and find a modern *C++* tutorial. If your C++ teacher told you to use `string.h`, then throw them out too. – Silvio Mayolo Jul 04 '21 at 20:20
  • 4
    Yes, `std::string` is the right way to store strings in C++. The functions you were using before (`strlen` and `strrev`) are C functions that don't work on C++ strings. Read up on `std::string` and use the functions that work with it. Mixing C and C++ is just a recipe for disaster. – Silvio Mayolo Jul 04 '21 at 20:22

2 Answers2

3

As other people have recommended, a simple solution is to use std::string and not char [20], and then you can call method reverse() to do the job.

Here is my simple code:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string str, str2;

    std::cout << " Please Enter The String : \n";
    std::cin >> str;    

    str2 = str;
    
    reverse(str.begin(), str.end());
    
    if( str == str2 )
        std::cout << "Palindrome"; 
    else
        std::cout << "Not a palindrome";

    return 0;
}

I have tested and verified that the code works.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Job_September_2020
  • 858
  • 2
  • 10
  • 25
0

strrev is a nonstandard C function it makes the reversal in-place. So the assignment makes no sense. strcpy + strcmp might have been appropriate.

Since you tagged this c++ You really want to use std::string to make things more concise.

#include<string>
#include<iostream>
#include<algorithm>
int main(){
    std::string in1, palindrome;
    std::cin >> in1;
    palindrome = in1;
    // reverse palindrome with std::reverse
    // compare with == for like contents. 
}
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67