Sep 16, 2008

C palindrome

a hastily done program that takes a string as input and checks if it is a palindrome. I wrote this on request, and looking back I can see that it is indeed very sloppy code. I would not recommend it for anything serious because the memory management here is just awful! However, I suppose it will do for a beginner programmer looking to cheat a little. Compiles on Turbo C/C++

I think I put it up for the sole purpose of testing Google's code prettifier.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>

int main(void)
{
char input[MAX_LEN],buffer[MAX_LEN],bufferrev[MAX_LEN];
int i=0,j=0;

printf("Enter your test string\n");
gets(input);

//Sanitize and remove spaces from input, if any.

do
{
if(!isspace(input[i]) && !ispunct(input[i])){
buffer[j]=input[i];
j++;
}
i++;
} while (input[i]!='\0');

buffer[j]='\0'; //append null character to end. Required for
//string.h functions to operate properly.

//end sanitation code

strcpy(bufferrev,buffer); //copy contents of buffer to bufferrev
strrev(bufferrev);        //reverse bufferrev. provided by string.h

if(strcmp(buffer,bufferrev)==0)
printf("\"%s\" is a palindrome!\n");
else
printf("\"%s\" is not a palindrome!\n");

getch();
return 0;
}

0 Comments:

Post a Comment