Thread: C++ problem
View Single Post
Old 03-09-2005, 06:38 PM   #6 (permalink)
fitzjj
 
Ultra Techie

Join Date: Oct 2003

Posts: 544

fitzjj

Default

Code:
#include<iostream>
#include<iomanip>
#include<cctype>

using namespace std;

int main() {
        int count=0,d=0,noChars=0;
        char array[count]; //you want to read in a string of chars not a number
        cout << "Enter a number: ";

        for(count=0;;count++){
                cin >> array[count];
                if(!isdigit(array[count]))
                break;
        }
        count--; //to remove whatever non digit was used to terminate the for loop
        noChars = count;        //you are changing count in the following loop so
                                //cannot use it in the last if statement


        for(int check=0; check<count; check++,count--){
                if(array[check]==array[count]){
                        d++;
                }else{
                        cout << "the number is not a palindrome" << endl;
                        break;
                }

                if(d==noChars/2)
                        cout << "the number is a palindrome" << endl;
        }
        return 0;
}
I was feeling generous today - it's still not perfect though - it will not deal correctly with palindromes with an even number of characters but that shouldnt take too long to fix.

A couple of pointers:
1. You want to check characters at either end of a number, so you need to be using a character array not a long int. Dont be fooled into thinking that you have to use a number data type just because it is a number. If you are not doing mathematical calculations on it then you can use a char[].

2. You are terminating your first loop by entering a non digit, so you want to subtract this from count

3. break is not tidy! - Ok im a java programmer and in java it is not considered 'good code' to use a break (perhaps it is in C++) but you should always think of ways out of your loop rather than relying on break.

I assume this was some homework of some sort, so i shouldnt have done as much for you as i have, so at least try and understand wat is going on else you are wasting your time - changes some things, see what happens, try and fix the bug that is still in the program!
fitzjj is offline