Tren Abern
Tren Abern

Reputation: 3

C++ program to check if a given string is a palindrome

The problem here is that it can't be a string from user input. There are 7 strings, 6 of them are numbers and one is a word "abba". I have so far written much of the code but I'm having trouble finding a way to test the 7 strings that I must use for the program.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>

using namespace std;

bool isNumPalindrome(string str);

int main ()
{
    string str;
    str = "10", "32", "222", "abba", "444244", "67867876", "123454321";
    int userExit;

    bool isNum = isNumPalindrome;

    if (isNumPalindrome)
    {
        cout << str << " is a palindrome";
        cout << endl;
    }
    else
    {
        cout << str << " is not a palindrome";
        cout << endl;
    }

    cout << "Press any key to exit: ";
    cin >> userExit;
    cout << endl;

    return 0;
}

bool isNumPalindrome(string str)
{
    int length = str.length();

    for (int i = 0; i < length / 2; i++)
        if (str[i] != str[length - 1 - i])
            return false;

        return true;
}

As you can see, I haven't quite figured out how to perform a function in main to take the return and output a statement. I need to find out how to test multiple strings, and then how to use the return statement to print something like cout << str << " is not a palindrome.";

Upvotes: 0

Views: 12405

Answers (2)

Muckle_ewe
Muckle_ewe

Reputation: 1123

string str;
str = "10", "32", "222", "abba", "444244", "67867876", "123454321";

change to

std:vector< std::string > vecOfStrings = { "10", "32", "222", "abba", "444244", "67867876", "123454321" };

Then just loop through the vector and pass each string to the function

for (unsigned int i = 0; i < vecOfStrings.size(); i++) {
    if ( isNumPalindrome( vecOfStrings[i] ) ) {
        // do something
    }
}

Upvotes: 0

vonbrand
vonbrand

Reputation: 11791

Your use of str = "one", "two", "three"; gets str set to "three"... the , operator does that. Besides, str can contain one string, trying to asign more just doesn't work. The name IsNumPalindrome you asign to the (non-defined) variable IsNum is a pointer to a function, if you then ask if(IsNum) it won't ever be the null pointer, so always true.

I could go on. There seems to be hadrly a line without gross errors or grave misunderstandings of C++.

Upvotes: 3

Related Questions