-1

My instructor asked me to make a program using cstring that checks if program is palindrome. why its giving me "Argument of type "char" is incompatible with parameter of type "const char" error.

#include <iostream>
#include <cstring>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string str = "";
    int strcmpVal;
    int length = str.length();
    cout << "******************************" << endl;
    cout << "PALINDROME" << endl;
    cout << "******************************" << endl;
    cout << "Enter a word: ";
    getline(cin, str);
    char* cStr = new char[str.length() + 1];
    strcpy(cStr, str.c_str());
    for (int i = 0; i < (length / 2); i++)
    {
        strcmpVal = strcmp(cStr[i],cStr[(length -1) -1]);
    }

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Albert
  • 33
  • 1
  • 3
  • 1
    Can you show the exact error message, in particular which line it is referring to? – Chelmy88 Sep 19 '19 at 14:59
  • 1
    "_"Argument of type "char" is incompatible with parameter of type "const char" error._" When asking about error messages, always copy-paste them, instead of trying to paraphrase them. There is no way, that the error is about trying to convert to `const char`, instead of `const char*`. `char` is not the same as pointer-to-`char`: `char*`. – Algirdas Preidžius Sep 19 '19 at 15:01

2 Answers2

1

For starters this statement

int length = str.length();

does not make sense because the object str is yet empty. You have to calculate the length after a string will be entered.

The standard C function strcmp compares strings not single characters. That is the type of the expression cStr[i] is char while the function awiats an argument of the type char * that would have the expression cStr if is passed to the function.

So use instead this loop

size_t i = 0;
size_t length = str.length();
while ( i < length / 2 && cStr[i] == cStr[length - i - 1] ) i++;

if ( i == length / 2 ) std::cout << "The string is a palindrome.\n";

Take into account that these statements

char* cStr = new char[str.length() + 1];
strcpy(cStr, str.c_str());

are redundant.

You could just write

const char *cStr = str.c_str();

Otherwise you need to free allocated memory after it is not used any more.

delete [] cStr;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0
strcmp(cStr[i], cStr[(length - 1) - 1]);

cStr[i] is a char, but the arguments of strcmp must be char*s (pointer to char).

But using strcmp is wrong here anyway, you just want to compare char, therefore you need rather:

strcmpVal = cStr[i] == cStr[(length -1) -1]);

But there are more issues. I let this as an exercise.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115